问题描述:

This question already has an answer here:

  • Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

    12 answers

网友答案:

String extends Object so that works but generics does not work that way.

Good explanation here http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html

网友答案:

Java uses copy by values which means you can safely do this

String s = "Hello";
Object o = s;
o = 5; // `s` is not corrupted by this.

However you can't change something which references a different type.

Map<String, String> map = new HashMap<>();
map.put("hi", "hello");
Map<String, Object> map2 = (Map) map;
map2.put("hi", 5); // map now has an Integer value in it.

String s = map.get("hi"); // ClassCastException.

This is why you cannot safely pass an Map<String, String[]> as an Map<String, Object[]> because the latter would let you do

Object[] os = new Integer[1];
param.put("hi", os); // Your Map<String, String[]> is corrupted.
网友答案:

You need a exact match of the type parameters of the relevant class. This means Map<String, String[]> is not assignable to Map<String, Object>. To make your code work use a wildcard:

public void getParameters(Map<String, ? extends Object> param){

}

or in this case simply

public void getParameters(Map<String, ?> param){

}
相关阅读:
Top