Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java List vs ArrayList

Tags:

java

generics

As a C++ oldtimer I have managed to solve my problem but I can not wrap my head around the underlying Java mechanisms here:

Vector<Object> x = new Vector<Object>();        // OK
ArrayList<Object> y = new ArrayList<Object>();  // OK
List<Object> zzz = new ArrayList<Object>();     // OK solves problem below but question remains
List<Object> z = new List<Object>();            // WHY? Compiler error: Cannot instantiate 
like image 637
Adam Avatar asked Feb 16 '12 09:02

Adam


2 Answers

The List is an interface. You cannot create in instance of an interface using new operator. That's why the line List<Object> z = new List<Object>(); gives error. Only classes can be instantiated.

like image 172
Santosh Avatar answered Nov 16 '22 03:11

Santosh


Yes. Because List is an Interface and in Java you cannot instantiate an Interface. You can only instantiate a class.

ArrayList is a class that's implementing List<> that's why you can instantiate it. :)

like image 40
Bryan Giovanny Avatar answered Nov 16 '22 02:11

Bryan Giovanny