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.
A List
in java is an interface that defines certain qualities a "list" must have. Specific list implementations, such as ArrayList
implement this interface and flesh out how the various methods are to work. What are you trying to accomplish with this list? Most likely, one of the built-in lists will work for you.
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.
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.
A List
isn't a real thing in Java. It's an interface, a way of defining how an object is allowed to interact with other objects. As such, it can't ever be instantiated. An ArrayList
is an implementation of the List
interface, as is a linked list, and so on. Use those instead.
Use List<Integer> list = new ArrayList<Integer>();
Source: Stackoverflow.com