java 中的“^=”运算符是什么
what is '^=' operator in java
我的代码如下:
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);
那么,我的代码就可以运行了。
'^='和'* = ^'有区别吗??为什么我搜索这个关于'^='的问题,它说它们是相同的??
What is the '^=' operator?
您需要将 ch
声明为 int
,或者将按位异或 ^=
的结果存储在 int
字段中。现在它正试图将它存储在 char
中,这是错误的来源。
从功能上看,它们是一样的:都是异或。
但数据类型不同:
如果我做 x = x ^ y
,x ^ y
的数据类型总是 int
或更大。当结果分配给更小的东西时,你必须投。
如果我这样做 x ^= y
,数据类型不会增长,因为赋值“知道它的类型”。
有关详细信息,请参阅 https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2 中的语言规范。
我的代码如下:
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);
那么,我的代码就可以运行了。
'^='和'* = ^'有区别吗??为什么我搜索这个关于'^='的问题,它说它们是相同的??
What is the '^=' operator?
您需要将 ch
声明为 int
,或者将按位异或 ^=
的结果存储在 int
字段中。现在它正试图将它存储在 char
中,这是错误的来源。
从功能上看,它们是一样的:都是异或。
但数据类型不同:
如果我做
x = x ^ y
,x ^ y
的数据类型总是int
或更大。当结果分配给更小的东西时,你必须投。如果我这样做
x ^= y
,数据类型不会增长,因为赋值“知道它的类型”。有关详细信息,请参阅 https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.26.2 中的语言规范。