This week's book giveaway is in the Clojure forum.
We're giving away four copies of Clojure in Action and have Amit Rathore and Francis Avila on-line!
See this thread for details.
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

polymorphism

 
Joshua Fix
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?

Thanks!
 
Joshua Fix
Ranch Hand
Posts: 57
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I stumbled across a website that explains it beautifully:

http://www.faqs.org/docs/think_java/TIJ313.htm

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.

cheers
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic