Cannot instantiate the type List [duplica

2019-01-05 02:56发布

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?

5条回答
ら.Afraid
2楼-- · 2019-01-05 03:13

Interfaces can not be directly instantiated, you should instantiate classes that implements such Interfaces.

Try this:

NameValuePair[] params = new BasicNameValuePair[] {
        new BasicNameValuePair("param1", param1),
        new BasicNameValuePair("param2", param2),
};
查看更多
Root(大扎)
3楼-- · 2019-01-05 03:15

List is an interface. Interfaces cannot be instantiated. Only concrete types can be instantiated. You probably want to use an ArrayList, which is an implementation of the List interface.

List<Product> products = new ArrayList<Product>();
查看更多
对你真心纯属浪费
4楼-- · 2019-01-05 03:15

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

查看更多
The star\"
5楼-- · 2019-01-05 03:26

Use a concrete list type, e.g. ArrayList instead of just List.

查看更多
叼着烟拽天下
6楼-- · 2019-01-05 03:30

List is an interface. You need a specific class in the end so either try

List l = new ArrayList();

or

List l = new LinkedList();

Whichever suit your needs.

查看更多
登录 后发表回答