コードがあります (マップ インターフェイスをテストしています)。
これが私の主な方法です:
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