以下代码显示如何实现equals()和hashCode()方法
class Point { private int x; private int y; public Point(int x, int y) { this.x = x; this.y = y; } public boolean equals(Object otherObject) { // Are the same? if (this == otherObject) { return true; } // Is otherObject a null reference? if (otherObject == null) { return false; } // Do they belong to the same class? if (this.getClass() != otherObject.getClass()) { return false; } // Get the reference of otherObject in a SmartPoint variable Point otherPoint = (Point) otherObject; // Do they have the same x and y co-ordinates boolean isSamePoint = (this.x == otherPoint.x && this.y == otherPoint.y); return isSamePoint; } public int hashCode() { return (this.x + this.y); } } public class Main { public static void main(String[] args) { Point pt1 = new Point(10, 10); Point pt2 = new Point(10, 10); Point pt3 = new Point(12, 19); Point pt4 = pt1; System.out.println("pt1 == pt1: " + (pt1 == pt1)); System.out.println("pt1.equals(pt1): " + pt1.equals(pt1)); System.out.println("pt1 == pt2: " + (pt1 == pt2)); System.out.println("pt1.equals(pt2): " + pt1.equals(pt2)); System.out.println("pt1 == pt3: " + (pt1 == pt3)); System.out.println("pt1.equals(pt3): " + pt1.equals(pt3)); System.out.println("pt1 == pt4: " + (pt1 == pt4)); System.out.println("pt1.equals(pt4): " + pt1.equals(pt4)); } }
上面的代码生成以下结果。
这里是equals()方法的实现的规范。假设x,y和z是三个对象的非空引用。
Java面向对象设计 -Java哈希码Object的哈希码哈希码是一个整数值。计算整数的算法称为散列函数。Java使用散列码从基于散列的集合...
Java面向对象设计 -Java静态内部类静态成员类不是内部类在另一个类的主体中定义的成员类可以声明为静态。例子以下代码声明了顶级...
Java面向对象设计 - Java继承子类可以从超类继承。超类也称为基类或父类。子类也称为派生类或子类。从另一个类继承一个类非常简...
Java面向对象设计 - Java抽象类和方法Java可以定义一个类,其对象不能被创建。它的目的只是表示一个想法,这是其他类的对象共有...
Java面向对象设计 -Java泛型方法和构造函数泛型方法我们可以在方法声明中定义类型参数,它们在方法的返回类型之前的尖括号中指定...