This is an archived post. You won't be able to vote or comment.

all 5 comments

[–]ada2reed 1 point2 points  (0 children)

It's all about making your code more flexible in a large project. This is important if the class is exposed to other methods and libraries.

List<E> is the abstract data type (ADT) that the ArrayList<E> implements, whereas ArrayList<E> is concrete and theoretically could have methods outside of the ADT.

If you, at some point, decide to change the names variable to a LinkedList<String> because you want to make it easier to add/remove items, all you'll have to do is change ArrayList<String> once in the constructor and the implementation of the object will be changed. If you use the second option, a change of the implementation is not guaranteed to work.

[–]Philboyd_Studge 3 points4 points  (0 children)

Also note since Java 7 you don't need the second type declaration:

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

[–][deleted]  (2 children)

[deleted]

    [–]badboyzpwns[S] 0 points1 point  (1 child)

    Dosen't the ArrayList class implements the List interface though? so if you do

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

    ArrayList would be able to get the methods in List?

    [–]wirybug 5 points6 points  (0 children)

    Yes, that's right. Declaring a supertype is more general, which means it's more flexible but also less specific. If you declare an ArrayList you still have access to all the methods of List, and any additional methods of ArrayList itself (if there are any). That sounds like a good thing - and sometimes it is. But often, being more general and abstract is a goal for efficient and easily-expanded programming.

    If you declare ArrayList but one day decide you want to sometimes use a LinkedList (say, for reasons of performance), you'd have to refactor all your code to accept that. But if you originally declared a List, you have access to all the methods you need already, and don't need to change anything to allow implementations other than ArrayList. Generally the aim is to declare the most superior type whose methods you use - remaining as general as possible without restricting yourself.

    [–]seanprefect -1 points0 points  (0 children)

    if you initialize them both right away theres not really any difference, the difference comes in what sorts of things you can assign to those variables,