我的代码如下:
char ch = t.charAt(t.length() - 1);
// result of XOR of two char is Integer.
for(int i = 0; i < s.length(); i++){
ch = ch^s.charAt(i);
ch = ch^t.charAt(i);
}
return ch;
它抛出错误
Line 6: error: incompatible types: possible lossy conversion from int to char ch = ch^s.charAt(i);
Line 7: error: incompatible types: possible lossy conversion from int to char ch = ch^t.charAt(i);
2 errors
但是,当我改变
ch = ch^s.charAt(i);
ch = ch^t.charAt(i);
至
ch ^= s.charAt(i);
ch ^= t.charAt(i);
然后,我的代码就可以工作了。
“^=”和“* = ^”有不同吗?为什么我搜索这个关于“^=”的问题,它说它们是相同的?
最佳答案
从功能上看,它们是相同的:都执行异或。
但是数据类型不同:
如果我执行
x = x ^ y
,则x ^ y
的数据类型始终为int
或更大。当结果被分配给更小的东西时,你必须进行强制转换。如果我执行
x ^= y
,数据类型不会随着赋值“知道其类型”而增长。请参阅 https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2 上的语言规范了解更多详情。
关于java - java中的 '^='运算符是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60090710/