2

Could someone explain the meaning of the following code, especially ArrayList and List and why do we need to use both?

String [] forecastArray =
            {
                    "Today - Sunny - 35/30",
                    "Tomorrow - Foggy - 33/28",
                    "Wednesday - Cloudy - 33/26",
                    "Thursday - Sleepy - 30/24",
                    "Friday - Bunking - 36/34",
                    "Saturday - Trapped - 38/35",
                    "Sunday - Heavy Rain - 32/28"
            };
    List<String> myList = Arrays.asList(forecastArray);

    List<String> weekForecast = new ArrayList<>(myList);
2
  • 7
    Google polymorphism in Java Commented Feb 6, 2015 at 5:58
  • One point is missing in the answers so far: myList is a List backed by the forecastArray and is immuteable. You won't be able to change it. weekForecast is backed by a copy of that array and can be changed. Commented Feb 6, 2015 at 6:34

3 Answers 3

3

List is an interface. ArrayList is an implementation of that interface. It's generally recommended to program to the interface. That way you could switch to a LinkedList and not change a return type or other code later on. This is an example of polymorphism.

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

3 Comments

And the list returned by Arrays.asList`` is neither an ArrayList` nor a LinkedList - indeed, it's a type you don't have access to, so you can't use the actual type.
This info is great. My question is why do we need to pass it as Arrays.asList(forecastArray) instead of simply forecastArray.
ArrayList doesn't have a constructor that takes an array.
1

List is an interface. ArrayList is an implementation of that interface.

Basically here Arrays.asList(forecastArray) method returns a List but caller doesn't aware of which instance is returns. so first assign to list then try to initilize the Arraylist.

or You can do like as shown below.

List weekForecast = new ArrayList(Arrays.asList(forecastArray));

Comments

1

Elliot Frish has clearly explained the first part.

In your particular case,

List<String> myList = Arrays.asList(forecastArray);

List<String> weekForecast = new ArrayList<>(myList);

are not the same.

Because the List instance returned by Arrays.asList is not same as java.utils.ArrayList. ArrayList returned is a private static class inside Arrays class.

Since both ArrayLists (in Arrays as well as in collections) implement List interface, you can assign them to a List. Code to the interface :)

Note : ArrayList<String> myList = Arrays.asList(someArray); --> doesn't compile

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.