aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Why create ArrayList of type List? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Why create ArrayList of type List?" Watch "Why create ArrayList of type List?" New topic
Author

Why create ArrayList of type List?

Franz Fountain
Ranch Hand

Joined: Nov 15, 2006
Posts: 58
It's quite common to see code like:
List<String> myList = new ArrayList<String>();

My question is why not just do:
ArrayList<String> myList = new ArrayList<String>();


I don't see the advantage of using polymorphism in this case. I guess ArrayList doesn't have any methods that are not in the interface List or this would really cramp your style. Is the advantage because now if you want to change your implementation and use a LinkedList instead of an ArrayList that you can easily do that in one line? I don't think that's a very good reason and I haven't found any other.
Andy Morris
Ranch Hand

Joined: May 30, 2004
Posts: 78
Thinking about coupling might help you.

Perhaps your myList is an attribute of a class and it has getters or setters for it. If your declared type was ArrayList then you'd be forcing all users of your code to use that implementation type, when they shouldn't really have to. By specifying your dependency on the interface you vastly reduce the coupling.

This can also have large implications on testing - think if that type wasn't a List and it was some sort of connection instead, you could end up forcing all users of the code to depend on a specific type of Connection (e.g a JDBCConnection), whereas their test might want to test specific behaviour from the connection obj such as a FailingConnection that one doesn't depend on a database and two can help mock specific circumstances.

A test is just one type of user of your code, and therefore just one example of a benefit of this approach, but there could be all sorts of users of your code which could benefit from this also.

The point I'm trying to make is that by always programming to the interface it should make your code much more flexible.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Why create ArrayList of type List?
 
Similar Threads
Old Collections Syntax in java 1.5
ArrayList confusion
initialising in arrys in form bean
List question
Generics