3
List<Object> myList = new ArrayList<String>(); //(hint: no)
Map<Integer> myMap = new HashMap<int>(); // (hint: also no)

Why are the statements wrong in the above declarations?

Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
John Cooper
  • 7,343
  • 31
  • 80
  • 100

6 Answers6

5

For the first one, because Java generics are not covariant. So you can't even do:

ArrayList<Object> myList = new ArrayList<String>();

For more info, see this article: Java theory and practice: Generics gotchas.

For the second one, you cannot use primitives as the generic type.

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
5

1) What would happen if anyone added a Long to the list that is referenced by myList?

2) You can't have a primitive there.

Kaj
  • 10,862
  • 2
  • 33
  • 27
5

Let's look at the first example. Think of the operations you should be able to do on a List<Object>: Add, Remove, Retrieve any Object.

You're trying to fill those requirements with a collection that you can Add, Remove, and Retrieve only strings.

List<Object> myList = new ArrayList<String>();

// This should be valid based on the List<Object> interface but obviously
// MyClass isn't String...so what would the statement do?
myList.add(new MyClass());

The second is simply because Generics in Java don't support primitive types. For more information, you could check out:

java - Why don't Generics support primitive types?

Community
  • 1
  • 1
Justin Niessner
  • 242,243
  • 40
  • 408
  • 536
3
  1. The first is impossible. You can use a wildcard:

    List<?> myList = new ArrayList<String>();
    

    But now, your list is completely unusable. Adding, removing, etc doesn't compile anymore:

    myList.add(new Object()); // Error
    myList.add("error");      // Error
    
  2. You can't use primitives (int, double, ....) with generics. You have to use the wrapper class:

    HashMap<Integer> myHap = new HashMap<Integer>();
    
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
1

for the second example Map has 2 generic parameters a Key and Value but the following still wont work

Map<Integer,Object> myMap = new HashMap<int,Object>();

that because as said before primitive types don't work with java generics (besides generic types always derive from Object and type erasure translates all generic variables to type Object)

ratchet freak
  • 47,288
  • 5
  • 68
  • 106
1

For all things Java-Generics, refer to Angelika Langer. In this case, Is List<Object> a supertype of List<String>?

Even though Java does support auto-boxing, it doesn't automatically convert <int> to <Integer>. IMO this is partly to remind users that you can get nulls.

Dilum Ranatunga
  • 13,254
  • 3
  • 41
  • 52