How to initialize List<String> 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 class
es 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>();
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
.
Can't instantiate an interface but there are few implementations:
JDK2
List<String> list = Arrays.asList("one", "two", "three");
JDK7
//diamond operator
List<String> list = new ArrayList<>();
list.add("one");
list.add("two");
list.add("three");
JDK8
List<String> list = Stream.of("one", "two", "three").collect(Collectors.toList());
JDK9
// creates immutable lists, so you can't modify such list
List<String> immutableList = List.of("one", "two", "three");
// if we want mutable list we can copy content of immutable list
// to mutable one for instance via copy-constructor (which creates shallow copy)
List<String> mutableList = new ArrayList<>(List.of("one", "two", "three"));
Plus there are lots of other ways supplied by other libraries like Guava.
List<String> list = Lists.newArrayList("one", "two", "three");
List is an Interface, you cannot instantiate an Interface, because interface is a convention, what methods should have your classes. In order to instantiate, you need some realizations(implementations) of that interface. Try the below code with very popular implementations of List interface:
List<String> supplierNames = new ArrayList<String>();
or
List<String> supplierNames = new LinkedList<String>();