how to start a LinkedList with Arrays.asList()

Viewed 545

I am trying to create a LinkedList

LinkedList<String> cities=  Arrays.asList("NY","LA","Seattle","San francisco");

which gives a compiler error because Arrays.asList returns a List<String>

I know that I could create first a List<String> and then create the linked list passing to the firs list to constructor. e.g

List<String> cities=  Arrays.asList("NY","LA","Seattle","San francisco");
LinkedList<String> linkedCities = new LinkedList<>(cities);

how would I do it with Arrays.asList or any other method, to avoid having two lists in memory ?

2 Answers

For the record, you don't actually have two lists in memory. Arrays.asList() is just a wrapper around the passed array. But if you want to avoid the wrapper, you can construct an empty list and then populate it with a single Collections.addAll():

LinkedList<String> cities = new LinkedList<>();
Collections.addAll(cities, "NY", "LA", "Seattle", "San francisco");

tl;dr

Your call to Arrays.asList does not produce a LinkedList object. Square peg, round hole.

So either change your declared variable to List instead of LinkedList, or explicitly create a LinkedList via its constructor.

Either this:

List< String > list = Arrays.asList( "NY" , "LA" , "Seattle" , "San Francisco" ) ;

… or this:

LinkedList< String > list = 
        new LinkedList <>(
                List.of( "NY" , "LA" , "Seattle" , "San Francisco" )
        );

Details

To quote the Javadoc of Arrays.asList:

Returns a fixed-size list backed by the specified array.

This sounds a lot like an ArrayList, but the object returned by Arrays.asList is not an ArrayList, well, not a java.util.ArrayList. What you get is an instance of a private static class confusingly named ArrayList, nested in Arrays class. See source code in OpenJDK.

Here is a demo.

List < String > list = Arrays.asList( "NY" , "LA" , "Seattle" , "San francisco" );
String className = list.getClass().getName();

String javaUtilArrayListClassName = new ArrayList < String >().getClass().getName();

See that code run live at IdeOne.com.

list = [NY, LA, Seattle, San francisco]
className = java.util.Arrays$ArrayList
javaUtilArrayListClassName = java.util.ArrayList

If you want an ArrayList whole contents are copied from an array, pass to the constructor.

ArrayList < String > arrayList = new ArrayList <>( Arrays.asList( "NY" , "LA" , "Seattle" , "San francisco" ) );  

You asked:

I am trying to create a LinkedList

and

avoid having two lists in memory ?

In modern Java, the simplest way to create a mutable LinkedList using literal syntax is to create a list via List.of, to be passed to constructor of LinkedList.

LinkedList < String > linkedList =
        new LinkedList <>(
                List.of( "NY" , "LA" , "Seattle" , "San Francisco" )
        );
Related