本文介绍了Java泛型不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么泛型不能在我的机器上工作。为什么下面的代码在Eclipse中没有工作,而没有将类型转换为 String
。我正在使用Java 1.6
package com.withgeneric;
Preferences> Java> Compiler,并查找JDK兼容性。确保它至少1.5。
class Util {
//普通静态方法
public static< K,V>布尔比较(Pair p1,Pair p2){
return p1.getKey()。equals(p2.getKey())&&
p1.getValue()。equals(p2.getValue());
}
}
class SPair< K,V> {
私钥K;
私有V值;
//通用构造函数
public SPair(K key,V value){
this.key = key;
this.value = value;
}
//泛型方法
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; }
}
公共类GenericMethod {
$ b $ / **
* @参数args
* /
public static void main(String [] args){
Pair< Integer,String> p1 =新的SPair<(1,苹果); //给出错误
Pair< Integer,String> p2 =新SPair(2,梨); //给出错误
boolean same = Util。< Integer,String> compare(p1,p2);
// TODO自动生成的方法存根
}
}
Why Generics not working in my machine. Why below code not working in Eclipse without Type casting to the
String
. I am using Java 1.6package 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 } }
解决方案In eclipse, go to Window > Preferences > Java > Compiler and look up JDK compliance. Make sure it's at least 1.5.
这篇关于Java泛型不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!