Java – how to subclass the general ArrayList so that the instance of myarraylist will become a subclass of ArrayList?

I want to keep my subclass generic. All I want to change is the add (object) method of ArrayList to call ArrayList Add (null) without adding anything (the normal implementation of ArrayList will add null; I want it to do nothing)

Solution

In this case, you should take precedence over inherited combinations, because if you forget to override one method of adding / changing elements in ArrayList (for example, you can forget to override the collection), you can still use empty elements

However, since the problem is about how to subclass ArrayList, you can do this:

import java.util.ArrayList;

public class MyArrayList<T> extends ArrayList<T> {
    public boolean add(T element) {
        if (element != null) return super.add(element);
        return false;
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>