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" )
);