实现equals()
class Person {
String name;
int birthYear;
byte[] raw;
public boolean equals(Object obj) {
if (!obj instanceof Person)
return false;
Person other = (Person)obj;
return name.equals(other.name)
&& birthYear == other.birthYear
&& Arrays.equals(raw, other.raw);
}
public int hashCode() { ... }
}
foo.equals(null)
必须返回false
(null instanceof 任意类
总是返回false
)
- 覆盖
equals()
时,记得要相应地覆盖hashCode()
实现hashCode()
class Person {
String a;
Object b;
byte c;
int[] d;
public int hashCode() {
return a.hashCode() + b.hashCode() + c + Arrays.hashCode(d);
}
public boolean equals(Object o) { ... }
}
实现compareTo()
class Person implements Comparable<Person> {
String firstName;
String lastName;
int birthdate;
// Compare by firstName, break ties by lastName, finally break ties by birthdate
public int compareTo(Person other) {
if (firstName.compareTo(other.firstName) != 0)
return firstName.compareTo(other.firstName);
else if (lastName.compareTo(other.lastName) != 0)
return lastName.compareTo(other.lastName);
else if (birthdate < other.birthdate)
return -1;
else if (birthdate > other.birthdate)
return 1;
else
return 0;
}
}
- 总是实现泛型版本
Comparable
而不是实现原始类型Comparable
实现clone()
class Values implements Cloneable {
String abc;
double foo;
int[] bars;
Date hired;
public Values clone() {
try {
Values result = (Values)super.clone();
result.bars = result.bars.clone();
result.hired = result.hired.clone();
return result;
} catch (CloneNotSupportedException e) { // Impossible
throw new AssertionError(e);
}
}
}
- 使用
super.clone()
让Object
类负责创建新的对象
- 基本类型域都可以正确地复制了。同样,我们不需要去克隆
String
和BigInteger
等不可变类型
反转字符串
String reverse(String s) {
return new StringBuilder(s).reverse().toString();
}