Map <string,object>类型不适用于参数Map <string,string []>

时间:2016-03-23 18:56:19

标签: java generics

为什么我收到此错误

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

}

public void test(){

    Map<String,String[]> testMap = new HashMap<String,String[]>();

    getParameters(testMap);  // type is not applicable error here

}

因为我可以将String数组传递给对象,如下所示。有人可以解释一下吗?

public void getParameters(Object param){

}

public void test(){

    String[] testArray = new String[10];

    getParameters(testArray);

}

3 个答案:

答案 0 :(得分:2)

Java使用值复制,这​​意味着您可以安全地执行此操作

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

但是,您无法更改引用其他类型的内容。

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.

这就是为什么你不能安全地将Map<String, String[]>作为Map<String, Object[]>传递,因为后者会让你这样做

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

答案 1 :(得分:0)

String extends Object,这样可以正常工作,但泛型不会那样。

这里有很好的解释http://docs.oracle.com/javase/tutorial/extra/generics/subtype.html

答案 2 :(得分:0)

您需要完全匹配相关类的类型参数。这意味着Map<String, String[]>无法分配给Map<String, Object>。要使代码工作,请使用通配符:

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

}

或在这种情况下只是

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

}
相关问题