我有一个代码(我正在测试地图接口)。
这是我的主要方法:
import blue.*;
public class Test {
public static void main(String[] args) throws InterruptedException, java.io.IOException {
MapCollections.<String, Number>frequencyTable(args);
}
}
这是我MapCollections
使用的课程:
package blue;
import java.util.*;
import static java.lang.System.out;
public class MapCollections {
/**
* The Generic Method. K is String and V is Number.
*/
public static <K extends String, V extends Number> void frequencyTable(K[] args) {
int initialCapacity = 10;
// Now I pass the same types (K,V) to the getHashMap method
// but it doesn't work, I get compile error on the hm.put() call, see a little below...
// If I explicitly change K,V for String and Number it compiles fine, without errors
Map<K, V> hm = MapCollections.<K,V>getHashMap(initialCapacity);
// ... the error is
// error: method put in interface Map<K#2,V#2> cannot be applied to given types
hm.put("one", 1);
hm.put("two", 2);
};
public static <K, V> Map<K, V> getHashMap(int initialCapacity) {
return new HashMap<K,V>(initialCapacity);
};
}
错误是:
C:\java>javac Test.java
.\blue\MapCollections.java:13: error: method put in interface Map<K#2,V#2> cannot be applied to given
types;
hm.put("one", 1);
^
required: K#1,V#1
found: String,int
reason: actual argument String cannot be converted to K#1 by method invocation conversion
where K#1,V#1,K#2,V#2 are type-variables:
K#1 extends String declared in method <K#1,V#1>frequencyTable(K#1[])
V#1 extends Number declared in method <K#1,V#1>frequencyTable(K#1[])
K#2 extends Object declared in interface Map
V#2 extends Object declared in interface Map
我明白我不能传递K
,V
从一种方法到另一种方法,它们失去了意义。
1)但是为什么?
2) 是什么K#1, V#1, K#2, V#2
?为什么会出现额外的数量?
3)有没有一种方法可以按照我的意愿使用K
?V