HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavaCritical

How to initialize List<String> object in Java?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
objecthowjavainitializeliststring

Problem

I can not initialize a List as in the following code:

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 List

How can I instantiate List?

Solution

If you check the API for List you'll notice it says:

Interface List


Being 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, Vector

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:

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.