开发者

Can you extend ArrayList in Java?

Is it possible to make a child clas开发者_StackOverflow社区s that extends ArrayList? If so, how?


You can extend any class that is not final in Java. Having said that, you should avoid inheritance if there is no true is-a relationship. Consider composition for reuse. Read about Liskov substitution principle


Yes you can.

public class MyArrayList<E> extends ArrayList<E>
{
}

However, I'm not sure why you would want to do this.


As many other have said, yes, you can extend class ArrayList, but it is not something that you should normally do; it is not considered good practice in Java.

I'm mainly a Java programmer, but the past months I've also been working on C# code. It seems like it's a common idiom in C# to extend the standard collection classes if you need a collection of a specific type (I actually don't know if it is a common idiom in general - at least the people who wrote the code I'm working with are doing this all the time).

So if they have a class Person and they need a list of persons, they'd create a class PersonList that extends the C# equivalent of ArrayList<Person>.

The common idiom in Java would just to use ArrayList<Person> if you need a list of Person objects and not to create a specific subclass for this.

I'd advise you to stick to the common Java way of doing things, and not create your own subclasses of ArrayList or other collection classes.


ArrayList is not final class and it provides public constructor, so technically it can be extended.

But best practice is delegate rather than extend. See: Decorator pattern


Just try it out. The class is not final, it's constructor is public, so you can. However, it's probably no good idea for a beginner.

Most of the time, it's no good idea for anyone. Imagine you add some functionality and get ExtList1 extends ArrayList. A college of yours adds a different independent functionality, so you have ExtList2 extends ArrayList. Now you want them both at once and you're out of luck.

Or you need the same feature with a different base list implementation (maybe LinkedList, though it's virtually always wrong to use it). Again, out of luck.

These are all cases when delegation wins. It needn't be more verbose when someone has created the base already.


I'd only inherit from ArrayList, if there was a very good reason for doing exactly this. Maybe some really extreme performance requirements based on proper JMH benchmarks.


As others said, extending java lang data structures is a very bad idea. However, if you have some logic you want to isolate in a collection class, I would suggest bellow solution:

public class ProductCollection{

    ArrayList<Product> products;

    public Product getByCode(String code) {
       // ... your logic goes here.
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜