snippetjavaCritical
How to initialize List<String> object in Java?
Viewed 0 times
objecthowjavainitializeliststring
Problem
I can not initialize a List as in the following code:
I face the following error:
Cannot instantiate the type
How can I instantiate
List supplierNames = new List();
supplierNames.add("sup1");
supplierNames.add("sup2");
supplierNames.add("sup3");
System.out.println(supplierNames.get(1));I face the following error:
Cannot instantiate the type
ListHow can I instantiate
List?Solution
If you check the API for
Being an
If you check that link, you'll find some
All Known Implementing Classes:
Some of those can be instantiated (the ones that are not defined as
The 3 most commonly used ones probably are:
Bonus:
You can also instantiate it with values, in an easier way, using the
But note you are not allowed to add more elements to that list, as it's
List you'll notice it says:Interface ListBeing an
interface means it cannot be instantiated (no new List() is possible).If you check that link, you'll find some
classes that implement List:All Known Implementing Classes:
AbstractList, AbstractSequentialList, ArrayList, AttributeList, CopyOnWriteArrayList, LinkedList, RoleList, RoleUnresolvedList, Stack, VectorSome 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:
List supplierNames1 = new ArrayList();
List supplierNames2 = new LinkedList();
List supplierNames3 = new Vector();Bonus:
You can also instantiate it with values, in an easier way, using the
Arrays class, as follows:List supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));But note you are not allowed to add more elements to that list, as it's
fixed-size.Code Snippets
Interface List<E>List<String> supplierNames1 = new ArrayList<String>();
List<String> supplierNames2 = new LinkedList<String>();
List<String> supplierNames3 = new Vector<String>();List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");
System.out.println(supplierNames.get(1));Context
Stack Overflow Q#13395114, score: 892
Revisions (0)
No revisions yet.