I’ve recently been experimenting with extending collection objects instead of using composition for my domain objects. So for example I will use this:
public class Path extends ArrayList<PathElement> {
}
public static void main(String args[]) {
Path path = new Path();
path.add(new PathElement());
}
instead of:
public class Path {
private List<PathElement> pathElements = new ArrayList<PathElement>();
/* getter/setter*/
}
public static void main(String args[]) {
Path path = new Path();
path.getPathElements().add(new PathElement());
}
Is this a common/acceptable practice? Are there any drawbacks or better alternatives? One drawback I can see is that the implementation cannot be changed easily, so you cannot for example use a LinkedList instead of an ArrayList.
Your second approach is correct. You shouldn’t be extending the built-in data structure classes unless you are modifying their behavior or adding new behavior.
Even if you modify or add new behavior, your domain objects shouldn’t be extending them. Instead, create a separate class which extends the Map or List and use the new class in your domain object, as you shown in second code block.