0

When do I use List and when do I use ArrayList in Java? Please phrase in terms of practical situations where you would rather apply one over another. Thank you!

Edit : Also, LinkedList. Business situations where these are used, thanks, thats what's different about this question.

user3388925
  • 317
  • 2
  • 4
  • 9

2 Answers2

0

List is an interface. The other two are implementations of which. You mostly want to code against interfaces. That is you wil do something like

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

Later on in the coding process, you may find that LinkedList has better performance for your scenario, so you just need to change one single place. Or maybe you don't care which concrete implementation is used, you just need "some sort of list". Then you could use an injected List implementation. Like this:

class ExampleClass{
    private List<String> strList = null;

    // We don't know and we don't care if Array or Linked List.
    public ExampleClass( List<String> aList ){
        strList = aList;
    }

    //...
}

For the differences between the implementations, see the links given in the comments as "possible duplicate of ..." or the JavaDoc.

Fildor
  • 14,510
  • 4
  • 35
  • 67
-1

***There's no difference between list implementations in both of your examples. There's however a difference in a way you can further use variable myList in your code.

When you define your list as:

List myList = new ArrayList(); you can only call methods and reference members that belong to List class. If you define it as:

ArrayList myList = new ArrayList(); you'll be able to invoke ArrayList specific methods and use ArrayList specific members in addition to those inherited from List.

Nevertheless, when you call a method of a List class in the first example, which was overridden in ArrayList, then method from ArrayList will be called not the one in the List.

That's called polymorphism. You can read upon it.***

This answer was given by ATrubka here

Community
  • 1
  • 1
Katler
  • 507
  • 3
  • 11