I know with Lists you can instantiate them to an ArrayList, but is this generally a good idea?

Is it better to do 'List<?> list = new ArrayList<?>();' rather then 'ArrayList<?> aList = new ArrayList<?>();'?

4 Years
Discussion Span
Last Post by JamesCherrill

Unless there's some reason why to has to be an ArrayList, by declaring the variable as a List you allow the possibility of (eg) changing the implementation to a LinkedList sometime later, secure in the knowledge that you will not break any existing code.


to summarise: program to the interface, not the implementation.
It's one of the basic tenets of good programming practice.


^ yes.

ps: Exactly the same logic applies to defining the return type for a method.
If your method returns a collection of <X> in a particular order, just declare the method as returning a List and implement it internally however seems best at the time. Similarly, if it returns a collection in no particular order (but without duplicates) declare it as returning a Set.


^ again, yes. Or Set<Y extends X> where X is an interface. Lists implies order which may not be relevant or defined, so, for example, if you switch the implementation from a List to a Map (often happens) it's easy to return the keySet()

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.