我正在使用==运算符比较2个Java对象,有人可以解释为什么打印"b"而不是"a"?
public class punktAusfuehren {
Punkt p1 = new Punkt(19, 10);
Punkt p2 = new Punkt(5, 0);
public static void main(String[] args) {
new punktAusfuehren();
}
public punktAusfuehren() {
if (p1 == p2) {
System.out.println("a");
} else {
System.out.println("b");
}
if (p1 instanceof Punkt) {
System.out.println("c");
} else {
System.out.println("d");
}
}
}
Run Code Online (Sandbox Code Playgroud)
因为他们有不同的参考.==如果两个对象被相同的引用引用,则给出引用相等,以比较两个对象使用equals方法.喜欢
检查两个对象是否相等,但是必须重写equals 和hashCode方法,以定义相等性
p1.equals(p2) //
Run Code Online (Sandbox Code Playgroud)
示例Point类可能如下所示:
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
// accessors omitted for brevity
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Point point = (Point) o;
return x == point.x && y == point.y;
}
@Override
public int hashCode() {
return Objects.hash(x, y);
}
}
Run Code Online (Sandbox Code Playgroud)
编辑:
对于对象比较,equality(==)运算符应用于对象的引用,而不是它们指向的对象.当且仅当它们指向同一个对象或两者都指向null时,两个引用是相等的.请参阅以下示例:
Point x = new Point(3,4);
Point y = new Point (3,4);
Point z = x;
System.out.println(x == y); // Outputs false
System.out.println(x.equals(y) ); // Outputs true
System.out.println(x == z); // Outputs true
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |