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!!!
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
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... Dave.