0

Why can't I add any object here , I was hoping I would be allowed to add any kind of object in such a list.

List<?> l = new ArrayList<Object>();
l.add(new Object());
l.add(new String("hello"));
Praveen Kumar
  • 1,624
  • 5
  • 18
  • 21
  • 1
    The ? stands for some unknown type. Any parameter we assign would have to be a subtype of this unknown type. Since we don't know what type that is, we cannot pass anything in. So as per rule Object should be a subtype of ? and compiler doesn't know what this unknown type(?) is. The sole exception is null, which is a member of every type. – Syam S Jul 15 '14 at 11:05

1 Answers1

1

Why not just:

    List<Object> l = new ArrayList<>();
    l.add(new Object());
    l.add(new String("hello"));
MightyPork
  • 18,270
  • 10
  • 79
  • 133