This question already has an answer here:
I have the following code:
List<Product> product = new List<Product>();
The error:
Cannot instantiate the type List<Product>
Product
is an Entity in my EJB project. Why I'm getting this error?
This question already has an answer here:
I have the following code:
List<Product> product = new List<Product>();
The error:
Cannot instantiate the type List<Product>
Product
is an Entity in my EJB project. Why I'm getting this error?
Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.
Try this:
List
is an interface. Interfaces cannot be instantiated. Only concrete types can be instantiated. You probably want to use anArrayList
, which is an implementation of theList
interface.List can be instantiated by any class implementing the interface.By this way,Java provides us polymorphic behaviour.See the example below
List list = new ArrayList();
Instead of instantiating an ArrayList directly,I am using a List to refer to ArrayList object so that we are using only the List interface methods and do not care about its actual implementation.
Examples of classes implementing List are ArrayList,LinkedList,Vector.You probably want to create a List depending upon your requirements.
Example:- a LinkedList is more useful when you hve to do a number of inertion or deletions .Arraylist is more performance intensive as it is backed by a fixed size array and array contents have to be changed by moving or regrowing the array.
Again,using a List we can simply change our object instantiation without changing any code further in your programs.
Suppose we are using
ArrayList<String> value = new ArrayList<String>();
we may use a specific method of ArrrayList and out code will not be robust
By using
List<String> value = new ArrayList<String>();
we are making sure we are using only List interface methods..and if we want to change it to a LinkedList we simply have to change the code :-
List value = new ArrayList();
------ your code uses List interface methods.....
value = new LinkedList();
-----your code still uses List interface methods and we do not have to change anything---- and we dont have to change anything in our code further
By the way a LinkedList also works a Deque which obviously also you cannot instantiate as it is also an interface
Use a concrete list type, e.g.
ArrayList
instead of justList
.List is an interface. You need a specific class in the end so either try
or
Whichever suit your needs.