0

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

2

3 Answers 3

1

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 List as the type hasn't bound you to using any methods that are only on ArrayList and not available on, say, a LinkedList.

For example, if I did:

LinkedList<String> strings = new LinkedList<String>();
String s = strings.pop();

pop is exclusive to LinkedList, so I can't just change it directly to an ArrayList. I'd have to also change my code:

ArrayList<String> strings = new ArrayList<String>();
String s = strings.remove(strings.size() - 1);

But if I had just used the interface, I would've never used pop in the first place, so I could've just changed strings to 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, since List tells you it may contain duplicates and is ordered manually. But if this isn't particularly important and you can use Collection, you can even replace the lists with implementations of Set.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the detailed reply. Cleared all my doubts.
0

Yes, First one gives flexibility to change implementation later time with minimal changes on client.

Example, you can change ArrayList to LinkedList, but client will be minimally affected if it uses interface methods.

List<String> tempList = new LinkedList<String>();

Comments

0

Its called designing to interfaces. Your code will be flexible, if you define List as a parameter both ArrayList and LinkedList (or anything else implementing the interface List) can be used as underlying implementation.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.