Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it correct to use ArrayList or LinkedList instead of List when declaring variables/parameters? [duplicate]

Tags:

java

Assuming you have a class something like:

public class foo {
    private List<String> fooThings;

    public void doSomething(List<String> things) {
        // Do a bunch of things here
        // Possibly setting fooThings at some point as well
    }
}

Is it ever appropriate for declarations to specify the concrete class e.g. ArrayList instead of the List interface? If so, when?

Edit> This question has nothing to do with when to use a LinkedList and when to use an ArrayList. That is a separate question that is answered elsewhere. The question is about when declarations should be the interface (List) for clarity and when it should specify an implementation e.g. ArrayList because it matters given what the method is going to do or how the instance variable will be leveraged.

like image 437
Eric98118 Avatar asked Sep 24 '13 20:09

Eric98118


1 Answers

Normally you should only use the interface List to declare your structure. However, on the rare occasion you need to use a specific method that is only available for a certain implementation of List such as LinkedList or ArrayList then you should declare your list type explicitly. However, this limits flexibility and should be done sparingly.

like image 158
JNYRanger Avatar answered Nov 14 '22 22:11

JNYRanger