Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am trying to instantiate

LinkedList<?> op = new LinkedList<?>();

But I get error

Cannot instantiate the type LinkedList<?>

Why is it that this cannot be instantiated in Java?

share|improve this question
1  
What do you want to achieve? If you want a linked list that accepts any kind of object, new LinkedList<Object>() is the correct thing to do. –  Heinzi Apr 6 '13 at 12:17
add comment

1 Answer

up vote 4 down vote accepted

If you don't know what object type will be inside the list, why are you using generics? <?> means I don't know (<? extends Object>).

It's been a long time since I programmed in Java but my understanding is that wildcard generics are made to match something, e.g. when you are declaring a method parameter, you can use a wildcard so that different generics can be passed to it. Also, a variable can use a wildcard to accept different generic types.

However, when creating an instance, you have to supply a specific type. The wildcard just doesn't have any sense there.

That's why

List<?> list = new LinkedList();
List<?> list = new LinkedList<Object>();
List<?> list = new LinkedList<MyObject>();

Are all possible but

List<?> list = new LinkedList<?>();

isn't.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.