简体   繁体   English

与泛型一起使用时如何解决“二元运算符'+'的错误操作数”?

[英]How to solve “bad operand for binary operator '+' ” when used with Generics?

here is my code :这是我的代码:

class MyExample {

    public static <T,R> R myMethod(T x,R y){
        R z= x+y;// error occurs here
        
        return z;
    }

    public static void main(String args[])
    {
        Integer val = 10;
        String str="Hello World!";
        System.out.println(val+str);// this prints the expected result
        System.out.println(myMethod(10," Hello World!"));
    }

}

This code gives error:此代码给出错误:

bad operand for binary operator +二元运算符的错误操作数 +

When I concat val and str with + it works fine within the main block, But not inside the myMethod.当我用 + 连接 val 和 str 时,它在主块内工作正常,但不在 myMethod 内。

I don't understand why it happens.我不明白为什么会这样。

Java does not support operator overloading . Java 不支持运算符重载 The operator + is defined on seven of the eight primitive types ( char , byte , short , int , long , float and double ), as well as on String .运算符+定义在八种原始类型中的七种( charbyteshortintlongfloatdouble )以及String

The types T and R are unbounded, therefore they are erased with Object .类型TR是无界的,因此它们被Object 擦除 Since + is not defined on Object , the compiler generates a compiler error.由于+未在Object定义,编译器会生成编译器错误。

System.out.println(val + str); works because the right side ( str ) of the expression is a String , hence the compiler tries to convert the left side ( val ) into a String .之所以有效,是因为表达式的右侧 ( str ) 是String ,因此编译器会尝试将左侧 ( val ) 转换为String Every class (at least implicitly) inherits from Object , therefore every class has an instance method toString() that is used to convert its instances to String s . 每个类(至少隐式地)都继承自Object ,因此每个类都有一个实例方法toString()用于将其实例转换为String s

As many people point out already Java does not allow operator overloading so you are bound to use the generic method where + is define.正如许多人指出的那样,Java 已经不允许运算符重载,因此您必须使用定义+的泛型方法。 T and R are erased with object meaning they are treated as object because the only common things between T and R are properties available in object, remember T and R for the compiler could be any arbitrary types. TR被对象擦除意味着它们被视为对象,因为TR之间唯一的共同点是对象中可用的属性,请记住,编译器的TR可以是任何任意类型。

The code below is not something i will suggest using, is more of a hack than anything else but it will let you compile, however is prone to many errors in runtime consider yourself warned下面的代码不是我建议使用的东西,它比其他任何东西都更像是一种黑客行为,但它可以让您编译,但是在运行时容易出现许多错误,请考虑一下自己的警告

class MyExample {

    public static <T ,R > R myMethod(T x, R y){
        return (R) (x.toString() + y.toString());
    }
    public static void main(String args[])
    {
        Integer val = 10;
        String str="Hello World!";
        System.out.println(val+str);// this prints the expected result
        System.out.println(myMethod(10," Hello World!"));
        System.out.println(myMethod("Hello World!", 10));
    }
}

the way that works is by using one of the 8 types where + is defined.工作方式是使用定义+的 8 种类型之一。 In the case above we are using String because any object has an string representation with the toString() method and then casting the type back to the return type R在上面的例子中,我们使用 String 因为任何对象都有一个带有toString()方法的字符串表示,然后将类型转换回返回类型R

Now I just to be completely clear the code posted here is just a hack to let you compile please do not use that code for any important code.现在我要完全清楚这里发布的代码只是一个让您编译的黑客,请不要将该代码用于任何重要代码。

So to be honest I would recommend you to rather ask for the behavior you are trying to archive and not about how to fix your current solution since this will only lead to extremely advance code and who knows maybe you need something way simpler.因此,老实说,我建议您宁愿询问您尝试存档的行为,而不是询问如何修复您当前的解决方案,因为这只会导致非常先进的代码,谁知道您可能需要更简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM