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<?>();'?

Recommended Answers

All 5 Replies

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.

hmm, I'd always return List<Y> where X implements Y :)

^ 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()

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.