java - 泛型编译错误。无法修复
问题描述
我正在尝试学习泛型并遇到了这个问题。我很困惑为什么代码不起作用
public class Test {
public static void main(String args[]) {
int result;
result = printValues(new Pair<String, Double>("Pair1", 3.0), new
Pair<String, Double>("Pair2", 4.0));
System.out.println(result);
}
public static <K, V extends Integer> int printValues(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getValue() + p2.getValue();
}
class Pair<K, V> {
private K key;
private V value;
public Pair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public V getValue() {
return value;
}
public void setKey(K key) {
this.key = key;
}
public void setValue(V value) {
this.value = value;
}
}
}
我收到以下编译错误:Test 类型中的方法 printValues(Test.Pair, Test.Pair) 不适用于参数 (Test.Pair, Test.Pair) 我尝试将方法 printValues 更改如下:
public static <K, V extends Number> int printValues(Pair<K, V> p1, Pair<K, V> p2) {
return p1.getValue() + p2.getValue();
}
但是错误是“未定义参数类型 V、V 的运算符 +”
编辑:
public static <K, V extends Number> int printValues(Pair<K, V> p1,
Pair<K, V> p2) {
return p1.getValue().intValue() + p2.getValue().intValue();
}
现在我在 printValues 上遇到错误(新对
没有可访问类型 Test 的封闭实例。必须使用 Test 类型的封闭实例来限定分配(例如 xnew A(),其中 x 是 Test 的实例)。
解决方案
您的代码几乎没有问题
new Pair<String, Double>
不适用于<K, V extends Integer>
asDouble
doesn't extendInteger
。一种方法是Number
根据此答案重新定义方法以考虑 Number 的不同实现:public static <K, V extends Number> Number printValues(Pair<K, V> p1, Pair<K, V> p2) { if(p1.getValue() instanceof Double || p2.getValue() instanceof Double) { return new Double(p1.getValue().doubleValue() + p2.getValue().doubleValue()); } else if(p1.getValue() instanceof Float || p2.getValue() instanceof Float) { return new Float(p1.getValue().floatValue() + p2.getValue().floatValue()); } else if(p1.getValue() instanceof Long || p2.getValue() instanceof Long) { return new Long(p1.getValue().longValue() + p2.getValue().longValue()); } else { return new Integer(p1.getValue().intValue() + p2.getValue().intValue()); } }
该类
Pair
应声明为静态,以便您可以在静态main()
方法中使用它:static class Pair<K, V> {
无需在对象上声明泛型类型,从 Java 7 开始使用
<>
运算符就足够了:Number result = printValues(new Pair<>("Pair1", 3.0), new Pair<>("Pair2", 4.0));
推荐阅读
- dataweave - 如何使用嵌套的“地图”
- html - 从单元格的右下角将三个图像相互对齐
- python-3.x - 为什么我在 python 中找不到使用此方法的字符串?
- python - alphalens.utils 返回 KeyError: "None of [DatetimeIndex (['
, dtype='datetime64[ns]', freq=None)] 在 [index]" - android - 从对话框编辑文本中获取输入并在列表视图中显示
- javascript - 在同一类选择器 Bootstrap Modal 中获取值
- python - 转换 dtype('
我有一个 numpy 数组,其中包含由 pandas 数据框的 groupby 创建的文本数据和进一步的数据预处理。现在我想将我的数据放入模型中,但我收到以下错误消息:
ufunc 'add' did not contain a loop with signature matching types (dtype('<
- python - 加载 Python 库 libpython3.6m.so.1.0 pyinstaller Ubuntu Python 时出错
- python-3.x - 如何确定 pip3 为非用户安装安装二进制文件/脚本的位置?
- excel - 如何在以下代码 VBA 中执行暂停