File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Collection class question Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Collection class question" Watch "Collection class question" New topic
Author

Collection class question

Brandt Charles
Ranch Hand

Joined: Apr 17, 2006
Posts: 57

I have seen many times the following when constructing objects of a collection class (though similar instances could occur for any class):

Set myTree = new TreeSet();

Why not declare the data type as TreeSet like this:

TreeSet myTree = new TreeSet();

My thought on the first way of instantiating would be allowing myTree to use the methods of the Set interface. But TreeSet objects already implement that interface anyway.

Thanks for the clarification in advance or gentle nudges to where I might clear this up.


Green, green, green!
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
One reason is that if you are only interested in the fact that the class implements the Set interface, then you could change the actual type without affecting how the reference is used.

That is, if for a scenario you just need a simple set of items, then you could make the implementation a HashSet. But if the requirements change, and you need the items in the set to be listed in the order they were entered, you could change the implementation to a LinkedHashSet. If later you decide that you need the set ordered, you could change the implementation to a TreeSet.

But none of those changes have to affect how you use the reference if the type is Set.
[ February 12, 2007: Message edited by: Keith Lynn ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collection class question