I see (and always use) the List reference variable type when creating an ArrayList: List<String> myList = new ArrayList<String>();
I don't know why I do this. Don't get me wrong... I know the value of polymorphism and use it very frequently in projects/classes I create myself. But I've never been sure why I need to refer to my ArrayList as a List, when all I really ever want is an ArrayList.
After having studied for SCJP, I learned that PriorityQueue and TreeSet both offer built-in sorting and my be potential solutions for something I'm trying to solve at work. So I was testing some code and created myself a TreeSet object:
Set<String> mySet = new TreeSet<String>();
I suddenly realized that although I had a method to add(), I could find absolutely no method to retreive an element from my set, other than an iterator. Stunned, I declared it with a TreeSet reference variable and saw the first() and last() methods wich solved my problem beautifully.
So now I use this:
TreeSet<String> mySet = new TreeSet<String>();
This made me question why I use List for ArrayLists. I went backed an looked very briefly, and it appeared that I was in fact loosing several ArrayList-specific methods by using the List reference type.
Can somebody help me out?
Joined: Sep 18, 2007
I stumbled across a website that explains it beautifully:
It's pretty long and the interesting collection information starts about half way down. Although it looks like it was written for 1.4 and doesn't include generics, it explains the benefits of being able to change the implementation of your code with minimal effort.
Also, it appears that the apporpriate polymorphic way to refer to a TreeSet is with a SortedSet interface reference variable. This gives you access to the set methods without having to downcast.