How to initialize List object in Java?

If you check the API for List 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:

AbstractListAbstractSequentialListArrayListAttributeListCopyOnWriteArrayListLinkedListRoleListRoleUnresolvedListStackVector

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

Bonus:
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");
System.out.println(supplierNames.get(1));

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

Leave a Comment