Alex Rivera | Logout

Why are variables declared with their interface name in Java?

Asked 2009-09-27T20:50:17.520
18

This is a real beginner question (I'm still learning the Java basics).

I can (sort of) understand why methods would return a List<String> rather than an ArrayList<String>, or why they would accept a List parameter rather than an ArrayList. If it makes no difference to the method (i.e., if no special methods from ArrayList are required), this would make the method more flexible, and easier to use for callers. The same thing goes for other collection types, like Set or Map.

What I don't understand: it appears to be common practice to create local variables like this:

List<String> list = new ArrayList<String>();

While this form is less frequent:

ArrayList<String> list = new ArrayList<String>();

What's the advantage here?

All I can see is a minor disadvantage: a separate "import" line for java.util.List has to be added. Technically, "import java.util.*" could be used, but I don't see that very often either, probably because the "import" lines are added automatically by some IDE.

Edit
Report

1 Answer

1

if later you want to change implementation of the list and use for example LinkedList(maybe for better performance) you dont have to change the whole code(and API if its library). if order doesnt matter you should return Collection so later on you can easily change it to Set if you would need items to be sorted.

answered 2009-09-27T20:54:07.413

Your Answer