0

I'm trying to build a container type called ListNamed, which is essentially a list, but one that allows element lookups by name, where multiple elements can have the same name, and in which case the lookup would return the first element found with a matching name (that's why I can't use a HashMap -> order matters, and keys are not-unique).

My initial version, which works:

public class ListNamed<T extends Named> extends ArrayList<T>{

    public T get(String name){
        for (T x: this){
            if (x.getName().equals(name)){
                return x;
            }
        }
        return null;
    }
}

However, there are cases where I would like to specify a different implementation of List - Instead of ArrayList, there are cases where I would like to use LinkedList.

So, is there a way to specify the extended implementation via generics, or will I have to create separate classes (ArrayListNamed, LinkedListNamed)?

  • I would strongly argue that you should be using composition rather than inheritance here. This `ListNamed` class isn't preserving the semantics of the underlying `List` interface, which could lead to odd behaviour in a polymorphic context. Composition would also give you the chance to trivially swap out the internal `List` implementation. – Oliver Charlesworth Oct 11 '14 at 23:59
  • Did you see [Map implementation with duplicate keys](http://stackoverflow.com/questions/1062960/map-implementation-with-duplicate-keys) already? Quote: [Learn from my mistakes...please don't implement this on your own.](http://stackoverflow.com/a/23609306/1744774) – Gerold Broser Oct 12 '14 at 00:01
  • Actually, my above comment is partially wrong; I guess this class *does* maintain `List` semantics, it just adds new methods. Nevertheless, composition might still be the solution to your problem here – Oliver Charlesworth Oct 12 '14 at 00:06
  • @GeroldBroser As far as I can tell, that Multimap is not ordered, and as stated in my question: order matters. – Goran Milovanovic Oct 12 '14 at 01:14
  • @OliverCharlesworth Wouldn't I have to basically re-implement all List methods? I mean, unless there's a way to tell Java to automatically call a method on a specific member, if that method is not found on the class, then that seems like it would be much more tedious than making a class per implementation. – Goran Milovanovic Oct 12 '14 at 01:22
  • 1
    @GoranMilovanovic [`com.google.common.collect.ArrayListMultimap`](http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ArrayListMultimap.html): _"When iterating through the collections supplied by this class, the ordering of values for a given key agrees with the order in which the values were added. "._ – Gerold Broser Oct 12 '14 at 18:23

0 Answers0