"Instantiating" a List in Java? [duplicate]
Trying to use the following code:
List<Integer> list = new List<Integer>();
I get the following error message:
java.util.List
is abstract; cannot be instantiated
What does this mean and why can't I initialize a List
the same way I would an ArrayList
?
Solution 1:
In Java, List
is an interface. That is, it cannot be instantiated directly.
Instead you can use ArrayList
which is an implementation of that interface that uses an array as its backing store (hence the name).
Since ArrayList
is a kind of List
, you can easily upcast it:
List<T> mylist = new ArrayList<T>();
This is in contrast with .NET, where, since version 2.0, List<T>
is the default implementation of the IList<T>
interface.
Solution 2:
List
is an interface, not a concrete class.
An interface is just a set of functions that a class can implement; it doesn't make any sense to instantiate an interface.
ArrayList
is a concrete class that happens to implement this interface and all of the methods in it.
Solution 3:
Use List<Integer> list = new ArrayList<Integer>();
Solution 4:
List
is the interface, not a class so it can't be instantiated. ArrayList
is most likely what you're after:
ArrayList<Integer> list = new ArrayList<Integer>();
An interface in Java essentially defines a blueprint for the class - a class implementing an interface has to provide implementations of the methods the list defines. But the actual implementation is completely up to the implementing class, ArrayList
in this case.
The JDK also provides LinkedList
- an alternative implementation that again conforms to the list interface. It works very differently to the ArrayList
underneath and as such it tends to be more efficient at adding / removing items half way through the list, but for the vast majority of use cases it's less efficient. And of course if you wanted to define your own implementation it's perfectly possible!
In short, you can't create a list because it's an interface containing no concrete code - that's the job of the classes that implement that list, of which ArrayList
is the most used by far (and with good reason!)
It's also worth noting that in C# a List
is a class, not an interface - that's IList
. The same principle applies though, just with different names.