-3

Is there any difference between LinkedList< ? > and LinkedList< Object > in Java?

karan
  • 93
  • 1
  • 12

1 Answers1

1

This passes compilation:

LinkedList<?> list1 = new LinkedList<String> ();

This doesn't:

LinkedList<Object> list2 = new LinkedList<String> ();

i.e. a LinkedList<?> variable can be assigned any LinkedList<SomeType>. A LinkedList<Object> variable can only be assigned a LinkedList<Object> (or a raw LinkedList, which is not advised to use).

On the other hand the following add:

LinkedList<?> list1 = new LinkedList<String> ();
list1.add("x");

doesn't pass compilation, while the following does:

LinkedList<Object> list2 = new LinkedList<Object> ();
list2.add("x");
Eran
  • 387,369
  • 54
  • 702
  • 768
  • Why cannot i add any string in list1? – karan Jun 06 '17 at 09:24
  • I think that main point here is that generics are _invariant_. It was done in order to save generics type safety, otherwise the following code might throw class cast exception: `List li = new ArrayList(); List ln = li; // illegal ln.add(new Float(3.1415));` So `?` was created for such purposes. – Alex Jun 06 '17 at 09:26
  • 2
    @karan Because `list1` may be assigned any generic LinkedList (`LinkedList`, `LinkedList`, etc...), so the compiler doesn't know which elements can be added to it safely. – Eran Jun 06 '17 at 09:29
  • @Eran thanks, it was helpful – karan Jun 06 '17 at 09:36