This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.
The problem
I can’t initialize a List as follows:
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
Copy the code
The following error will occur:
Cannot instantiate the type List<String>
Copy the code
How do I instantiate List
?
answer
Answer 1
If you look at the List API, you’ll notice:
Interface List<E>
Copy the code
An interface, meaning it cannot be instantiated (i.e., new List() cannot be done)
If you look at the API, you’ll find some implementation classes for List:
All known implementation classes: AbstractList AbstractSequentialList ArrayList AttributeList CopyOnWriteArrayList LinkedList RoleList, RoleUnresolvedList, Stack, Vector
These can be instantiated. You can learn more about them by looking at them: which one is best for your needs.
The three most commonly used are:
List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();
Copy the code
You can also use the Arrays class to instantiate from values in a simpler way, like this:
List<String> supplierNames = Arrays.asList("sup1"."sup2"."sup3");
System.out.println(supplierNames.get(1));
Copy the code
Note, however, that you can’t add any more elements to the List because it’s a fixed size.
Answer 2
You can’t instantiate the interface, but you can at least implement it:
JDK2
:
List<String> list = Arrays.asList("one"."two"."three");
Copy the code
JDK7
:
//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
Copy the code
JDK8
:
List<String> list = Stream.of("one"."two"."three").collect(Collectors.toList());
Copy the code
JDK9
:
// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one"."two"."three");
// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one"."two"."three"));
Copy the code
In addition, there are many other methods provided by libraries such as Guava.
List<String> list = Lists.newArrayList("one"."two"."three");
Copy the code
Translation content sources Stack Overflow:stackoverflow.com/questions/1…