为什么泛型在我的机器上不起作用。为什么下面的代码在没有类型转换的情况下无法在 Eclipse 中工作String
。我正在使用 Java 1.6
package com.withgeneric;
class Util {
// Generic static method
public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getKey().equals(p2.getKey()) &&
p1.getValue().equals(p2.getValue());
}
}
class SPair<K, V> {
private K key;
private V value;
// Generic constructor
public SPair(K key, V value) {
this.key = key;
this.value = value;
}
// Generic methods
public void setKey(K key) { this.key = key; }
public void setValue(V value) { this.value = value; }
public K getKey() { return key; }
public V getValue() { return value; }
}
public class GenericMethod {
/**
* @param args
*/
public static void main(String[] args) {
Pair<Integer, String> p1 = new SPair<>(1, "apple"); //Giving Error
Pair<Integer, String> p2 = new SPair<>(2, "pear"); //Giving Error
boolean same = Util.<Integer, String>compare(p1, p2);
// TODO Auto-generated method stub
}
}