Why are they not valid in Java?

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

Why are the statements incorrect in the above ads?

+3
source share
6 answers

Let's look at the first example. Think about the operations you must perform in List<Object>: add, delete, and retrieve any object.

You are trying to populate these requirements with a collection that allows you to add, delete, and retrieve only rows.

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());

Secondly, simply because Generics in Java do not support primitive types. For more information, you can check:

java - Why primitive types are not supported in Generics?

+5
source

For the first, since Java generics are not covariant. Therefore, you cannot even do:

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

. : Java: Generics gotchas.

, .

+5

1) , - Long , myList?

2) .

+5
  • . :

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

    . , .. :

    myList.add(new Object()); // Error
    myList.add("error");      // Error
    
  • (int, double,....) . :

    HashMap<Integer> myHap = new HashMap<Integer>();
    
+3

Map 2 a Key Value,

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

because, as said above, primitive types do not work with java-generics (besides the fact that generic types are always derived from Object and type erasure converts all generic variables to Object type)

+1
source

For all Java-Generics stuff, check out Angelika Langer. In this case, Is List <Object> supertype List <String>?

Although Java supports automatic boxing, it does not automatically convert <int>to <Integer>. IMO this partially reminds users that you can get zeros.

+1
source

All Articles