7

Is there any Difference between two lines in the following

 ArrayList<String> arrName =  new ArrayList<String>();
 List<String>      arrName =  new ArrayList<String>();
6
  • I've seen the same question (even same text) between yesterday and today (but can't find it). Commented Feb 20, 2013 at 7:51
  • @LuiggiMendoza. Even me. Commented Feb 20, 2013 at 7:54
  • Explanation here Commented Feb 20, 2013 at 7:54
  • Oops I haven't Seen it exists I am going to delete mine Commented Feb 20, 2013 at 7:55
  • @LloydSantos thanks, at least I know I'm not insane :) Commented Feb 20, 2013 at 7:55

6 Answers 6

4

Almost always the second one is preferred over the first one. The second has the advantage that the implementation of the List can change (to a LinkedList for example), without affecting the rest of the code. This is will be difficult to do with an ArrayList, not only because you will need to change ArrayList to LinkedList everywhere, but also because you may have used ArrayList specific methods.

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

Comments

3

Try to hide specific implementation behind an Interface whenever possible. see this

Comments

2

The second approach is usually the preferred one as it hides the implementation behind an interface.

This means that later on, if the requirements will change and will require another implementation of the List interface, you can change just one line of code and everything else will still work because you were coding to an interface not to a class.

Comments

2

There is not much difference per se, but List shall be used whenever possible as it is an interface and you may see in standard libraries' methods parameters are generally List<K>, so that any specific implementation can be passed, like ArrayList or LinkedList.

Comments

2

Second is example of Program to Interface and its the preferred way.
For details What does it mean to "program to an interface"?

Comments

2

The latter is usually recommended as long as you only need a List interface later on. That's called "programming to interface, not implementation".

As for the detailed difference between them, I have answered in another question on stackoverflow: The difference between "C c = new C()" and "A c = new C()" when C is a subclass of A in Java

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.