517

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

List<String> supplierNames = new List<String>();
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<String>

How can I instantiate List<String>?

Sartavius
  • 93
  • 2
  • 6
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
  • 2
    Does this answer your question? [How to make a new List in Java](https://stackoverflow.com/questions/858572/how-to-make-a-new-list-in-java) – fatimasajjad May 27 '22 at 15:40

13 Answers13

878

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:

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<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.

J.A.I.L.
  • 10,644
  • 4
  • 37
  • 50
  • 1
    Arrays.asList is great but as you should have noticed by now fails to do what one expects in cases like `int[] a = {1,2,3}; System.out.println(Arrays.asList(a)); // [[I@70cdd2]` – Mr_and_Mrs_D Apr 09 '14 at 23:02
  • 1
    @J.A.I.L. That's not what's happening. That's a list of one element, where the one element is an array of ints. The wanted behaviour was probably a list of three elements 1, 2, and 3. – Christoffer Hammarström Apr 27 '15 at 13:10
  • 2
    @Christoffer Hammarström to print a list or an array, you could use java.util.Arrays.toString(array);, so this feature is already given.. – Maxr1998 Jun 03 '15 at 13:00
  • @Maxr1998 I don't know what you're talking about, i meant that `[I@70cdd2` is the `.toString()` of an array of ints, not the memory address of a `List` like @J.A.I.L. said. – Christoffer Hammarström Jun 03 '15 at 13:19
  • @Christopher Hammarström toString prints the memory address. – Maxr1998 Jun 06 '15 at 20:21
  • My method prints the content. – Maxr1998 Jun 06 '15 at 20:41
  • 1
    Some discorage use of Vector like [this](http://www.javapractices.com/topic/TopicAction.do?Id=65) and [here](http://stackoverflow.com/questions/1792134/a-colleague-said-dont-use-java-util-vector-anymore-why-not). Because of threading issues – Nuno Rafael Figueiredo Dec 09 '15 at 17:49
  • 5
    If you need the resulting list to be an `ArrayList`, use `new ArrayList<>(Arrays.asList("sup1", "sup2", "sup3"))` – Daniel F Feb 21 '16 at 14:52
  • I have a method that returns `List` to a `List` working correctly. Anyone know how this is possible? `List tableList = getTableNames(sqlString);` – Andrew Kirna Nov 29 '17 at 17:37
  • @DanielF By default, the Arrays.asList method returns an ArrayList, there is no need to explicitly convert it to ArrayList – Akhil Mar 09 '21 at 06:54
  • @AkhilBaby It returns a `List` https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList(T...) see https://www.baeldung.com/java-arrays-aslist-vs-new-arraylist – Daniel F Mar 09 '21 at 19:00
  • @DanielF It is actually returning an ArrayList, but not java.util.ArrayList :) The returned one is an instance of java.util.Arrays.ArrayList - which is essentially a list backed by the immutable array – Akhil Mar 10 '21 at 09:16
198

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");
Pshemo
  • 122,468
  • 25
  • 185
  • 269
LazerBanana
  • 6,865
  • 3
  • 28
  • 47
43

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>();
Doseke
  • 861
  • 8
  • 15
18

You will need to use ArrayList<String> or such.

List<String> is an interface.

Use this:

import java.util.ArrayList;

...

List<String> supplierNames = new ArrayList<String>();
Ofir Farchy
  • 7,657
  • 7
  • 38
  • 58
15

List is an interface, and you can not initialize an interface. Instantiate an implementing class instead.

Like:

List<String> abc = new ArrayList<String>();
List<String> xyz = new LinkedList<String>();
Ankit
  • 3,083
  • 7
  • 35
  • 59
11

In most cases you want simple ArrayList - an implementation of List

Before JDK version 7

List<String> list = new ArrayList<String>();

JDK 7 and later you can use the diamond operator

List<String> list = new ArrayList<>();

Further informations are written here Oracle documentation - Collections

Daniel Perník
  • 5,464
  • 2
  • 38
  • 46
9

List is just an interface, a definition of some generic list. You need to provide an implementation of this list interface. Two most common are:

ArrayList - a list implemented over an array

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

LinkedList - a list implemented like an interconnected chain of elements

List<String> supplierNames = new LinkedList<String>();
Jakub Zaverka
  • 8,816
  • 3
  • 32
  • 48
7

Depending on what kind of List you want to use, something like

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

should get you going.

List is the interface, ArrayList is one implementation of the List interface. More implementations that may better suit your needs can be found by reading the JavaDocs of the List interface.

Uli
  • 574
  • 3
  • 12
7

If you just want to create an immutable List<T> with only one object in it, you can use this API:

List<String> oneObjectList = Collections.singletonList("theOnlyObject”);

More info: docs

Sakiboy
  • 7,252
  • 7
  • 52
  • 69
5

List is an Interface . You cant use List to initialize it.

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

These are the some of List impelemented classes,

ArrayList, LinkedList, Vector

You could use any of this as per your requirement. These each classes have its own features.

someone
  • 6,577
  • 7
  • 37
  • 60
  • Some discorage use of Vector like [this](http://www.javapractices.com/topic/TopicAction.do?Id=65) and [here](http://stackoverflow.com/questions/1792134/a-colleague-said-dont-use-java-util-vector-anymore-why-not). Because of threading issues – Nuno Rafael Figueiredo Dec 09 '15 at 17:48
3

Just in case, any one still lingering around this question. Because, i see one or two new users again asking the same question and everyone telling then , No you can't do that, Dear Prudence, Apart from all the answers given here, I would like to provide additional Information - Yes you can actually do, List list = new List(); But at the cost of writing implementations of all the methods of Interfaces. The notion is not simply List list = new List(); but

List<Integer> list = new List<Integer>(){

        @Override
        public int size() {
            // TODO Auto-generated method stub
            return 0;
        }

        @Override
        public boolean isEmpty() {
            // TODO Auto-generated method stub
            return false;
        }

        @Override
        public boolean contains(Object o) {
            // TODO Auto-generated method stub
            return false;
        }

..... and So on (Cant write all methods.)

This is an example of Anonymous class. Its correct when someone states , No you cant instantiate an interface, and that's right. But you can never say , You CANT write List list = new List(); but, evidently you can do that and that's a hard statement to make that You can't do.

voucher_wolves
  • 565
  • 10
  • 20
  • To be clear though, this doesn't create an object whose actual type is `List`. Rather, it declares a new class which has no name and implements `List`, and at run-time creates a new object of the newly-declared class. – Radiodef Jul 16 '18 at 00:53
3

Instead of :

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

Write this if you are using latest JDK:

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

It's the correct way of initializing a List.

0

We created soyuz-to to simplify 1 problem: how to convert X to Y (e.g. String to Integer). Constructing of an object is also kind of conversion so it has a simple function to construct Map, List, Set:

import io.thedocs.soyuz.to;

List<String> names = to.list("John", "Fedor");

Please check it - it has a lot of other useful features

fedor.belov
  • 22,343
  • 26
  • 89
  • 134