gpt4 book ai didi

java - 如何解决 "bad operand types for binary operator ' +' "错误

转载 作者:行者123 更新时间:2023-11-30 01:47:33 25 4
gpt4 key购买 nike

刚刚开始学习泛型的概念。但仍不清楚。我写的代码只是添加 2 个数字(整数)。它显示 - “二元运算符‘+’的操作数类型错误”。谁能帮助我理解这个错误?我该如何解决?

package Generics;

public class Class <T> {

public T a;
public T b;
public T z;

public T add(T a,T b){

this.a = a;
this.b = b;

z = a + b;

return z;
}



public static void main(String[] args) {

Class <Integer> obj1 = new Class <> ();


Integer result = obj1.add(5,6 );

System.out.println(result);

}
}

错误:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - bad operand types for binary operator '+'
first type: T
second type: T
at Generics.Class.add(Class.java:14)
at Generics.Class.main(Class.java:26)
C:\Users\userName\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)

最佳答案

首先:不要使用Class作为类名!这是误导。

这里 T 具有基本类型:Object
对象不能使用 + 运算符或任何算术运算符求和。
您只能使用原语或字符串(从 String 的任何一侧)执行此操作。
问题在于泛型是使用对象而不是基元进行类型化的。
因此您只能用作上限通配符:T extends Number
但仍然无法将 Number 求和,因为 Number 是对象。所以你应该获取它们的原始值(int、double 等)来实现这一点。

虽然很复杂并且有几个未经检查的转换,但你可以写一些东西:

public class Computation<T extends Number> {

private static Map<Class<? extends Number>, BinaryOperator<Number>> map = new HashMap<>();

static {
map.put(Integer.class, (a, b) -> Integer.valueOf(a.intValue() + b.intValue()));
map.put(Double.class, (a, b) -> Double.valueOf(a.doubleValue() + b.doubleValue()));
// and so for
}

private final Class<T> runtimeType;

public Computation(Class<T> runtimeType) {
this.runtimeType = runtimeType;
}

T add(T a, T b) {
return (T) map.get(runtimeType)
.apply(a, b);
// handle the not found value in the map case too
}

public static void main(String[] args) {
Computation<Integer> obj1 = new Computation<>(Integer.class);
Integer result = obj1.add(5, 6);
System.out.println(result);

Computation<Double> obj2 = new Computation<>(Double.class);
Double result2 = obj2.add(5.5, 6.4);
System.out.println(result2);
}
}

输出:

11

11.9

但是一个更简洁的解决方案(没有未经检查的转换,没有要处理的映射等等...),可能会引入一个接口(interface)Computation并为每个要处理的数字类型定义实现:

public interface Computation<T extends Number> {
T add(T a, T b);
}
public class IntegerComputation implements Computation<Integer>{
@Override
public Integer add(Integer a, Integer b) {
return a.intValue() + b.intValue();
}
}
public class DoubleComputation implements Computation<Double> {
@Override
public Double add(Double a, Double b) {
return a.doubleValue() + b.doubleValue();
}
}

关于java - 如何解决 "bad operand types for binary operator ' +' "错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57393302/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com