I can not initialize a List as in the following code:
List<String> supplierNames = new List<String>();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));
I face the following error:
Cannot instantiate the type
List<String>
How can I instantiate List<String>?
If you check the API for
Listyou’ll notice it says:Being an
interfacemeans it cannot be instantiated (nonew List()is possible).If you check that link, you’ll find some
classes that implementList:Some of those can be instantiated (the ones that are not defined as
abstract class). Use their links to know more about them, I.E: to know which fits better your needs.The 3 most commonly used ones probably are:
Bonus:
You can also instantiate it with values, in an easier way, using the
Arraysclass, as follows:But note you are not allowed to add more elements to that list, as it’s
fixed-size.