Possible Duplicate:
List versus ArrayList as reference type?
I read somewhere in StackOverflow that this:
List<String> foo = new ArrayList<String>();
is the best practice for initialization of ArrayList. And that this:
ArrayList<String> foo = new ArrayList<String>();
should be avoided. Is this correct? If yes can someone explain why is it so?
Thanks,
EG
This is how most developers use
ArrayList(myself included), and is a general tenet of polymorphism. You should use the highest class/interface in the class hierarchy that you can while still having all your functionality available.Generally, this makes your code more flexible, and you can switch out implementations more easily since you know that programming with
Listas the type hasn’t bound you to using any methods that are only onArrayListand not available on, say, aLinkedList.For example, if I did:
popis exclusive toLinkedList, so I can’t just change it directly to anArrayList. I’d have to also change my code:But if I had just used the interface, I would’ve never used
popin the first place, so I could’ve just changedstringsto whatever implementation I wanted.This is especially important when programming APIs. If your methods are publicly accessible and will be used by other developers, then you need to make sure that you aren’t restricting what kind of lists your methods take unless you have a good reason for doing so, especially since they may have a good reason for not wanting to use
ArrayList.If you’re doing nothing but iteration and adding/removing, you could even go up to
Collection. Here you start to lose context though, sinceListtells you it may contain duplicates and is ordered manually. But if this isn’t particularly important and you can useCollection, you can even replace the lists with implementations ofSet.