观察:
Java有一个逻辑与运算符。
Java有一个逻辑或运算符。
Java有一个逻辑NOT运算符。
问题:
sun表示,Java没有逻辑XOR运算符。我想定义一个。
方法定义:
作为一种方法,简单定义如下:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
方法调用:
这个方法的调用方式如下:
boolean myVal = logicalXOR(x, y);
操作符用法:
我更希望有一个操作符,使用如下:
boolean myVal = x ^^ y;
问题:
我找不到任何关于如何在Java中定义新操作符的内容。我该从哪里开始呢?
以下是你的代码:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
是多余的。
为什么不这样写:
public static boolean logicalXOR(boolean x, boolean y) {
return x != y;
}
?
而且,正如javashlook所说,已经有^ operator了。
!=和^对布尔操作数(你的情况)的作用相同,但对整数操作数的作用不同。
* Notes:
1. They work identically for boolean (primitive type), but not Boolean (object type) operands. As Boolean (object type) values can have value null. And != will return false or true when one or both of its operands are null, while ^ will throw NullPointerException in this case.
2. Although they work identically, they have different precedence, e.g. when used with &: a & b != c & d will be treated as a & (b != c) & d, while a & b ^ c & d will be treated as (a & b) ^ (c & d) (offtopic: ouch, C-style precedence table sucks).
以下是你的代码:
public static boolean logicalXOR(boolean x, boolean y) {
return ( ( x || y ) && ! ( x && y ) );
}
是多余的。
为什么不这样写:
public static boolean logicalXOR(boolean x, boolean y) {
return x != y;
}
?
而且,正如javashlook所说,已经有^ operator了。
!=和^对布尔操作数(你的情况)的作用相同,但对整数操作数的作用不同。
* Notes:
1. They work identically for boolean (primitive type), but not Boolean (object type) operands. As Boolean (object type) values can have value null. And != will return false or true when one or both of its operands are null, while ^ will throw NullPointerException in this case.
2. Although they work identically, they have different precedence, e.g. when used with &: a & b != c & d will be treated as a & (b != c) & d, while a & b ^ c & d will be treated as (a & b) ^ (c & d) (offtopic: ouch, C-style precedence table sucks).