Yajli Maclo Yajli Maclo - 1 year ago 112
Java Question

How to initialize List<String> object in Java?

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

List<String> supplierNames = new List<String>();

I face the following error:

Cannot instantiate the type

How can I instantiate

Answer Source

If you check the API for List http://docs.oracle.com/javase/6/docs/api/java/util/List.html you'll notice it says:

Interface List<E>

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

Those can be instantiated. 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<String> supplierNames1 = new ArrayList<String>();
 List<String> supplierNames2 = new LinkedList<String>();
 List<String> supplierNames3 = new Vector<String>();

You can also instantiate it with values, in an easier way, using the Arrays class, as follows:

List<String> supplierNames = Arrays.asList("sup1", "sup2", "sup3");

But note you are not allowed to add more elements to that list, as it's fixed-size.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download