File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes java.util package and the Collection API Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "java.util package and the Collection API" Watch "java.util package and the Collection API" New topic

java.util package and the Collection API

Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
Hello Folks
I am having a hard time understanding the following statement & concept can someone please explain me this.
There are three basic types of interfaces in Collection API, List, Map & Set. Why is recommended to refer the collection instances with reference variables of interface type rather than class type.
For example
Why is it preferred to do this
List aList = new ArrayList();
instead of
ArrayList aList = new ArrayList();
Thanks in advance For this!!!
Cindy Glass
"The Hood"

Joined: Sep 29, 2000
Posts: 8521
This really is not a Collections issue, it is an OO issue.
If you create a variable with a class type:
ArrayList aList = new ArrayList();
Then version 1.5 comes out with SuperDuperArrayList as a class, to use the new class you need to find EVERY use and reference to the variable and insure that it is updated to use the new class. Not a job to be undertaken lightly.
However if you use the interface that describes the functions that you want this variable to be able to do, such as:
List aList = new ArrayList();
when the new class comes out, you can easily swap it in:
List aList = new SuperDuperArrayList();
and still know that all of the places that reference or use aList will still function properly because it is STILL a List after all.

"JavaRanch, where the deer and the Certified play" - David O'Meara
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Also in terms of defining APIs that you may create. (this is just an extension to what Cindy said)
If you defined as part of your API a method with this signature:

If someone tried to use your functionality but they were using Vectors, they would have to move their data from a Vector to an ArrayList so they can use your function, then convert back from an ArrayList to a Vector. All of which would be wasted effort.
If you define it like this:

and only use the List functionality, then your API is compatible with both Vectors and ArrayLists (and anything else that implements the List interface!)
When possible I try to work to java.util.Collection rather than List, since it will support more classes if you can handle the reduced functionality support...
I agree. Here's the link:
subject: java.util package and the Collection API
It's not a secret anymore!