- String重写equals() 和 hashCode()
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (anObject instanceof String) {
String anotherString = (String)anObject;
int n = value.length;
if (n == anotherString.value.length) {
char v1[] = value;
char v2[] = anotherString.value;
int i = 0;
while (n-- != 0) {
if (v1[i] != v2[i])
return false;
i++;
}
return true;
}
}
return false;
}
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
System.out.println("a".hashCode());
System.out.println("ab".hashCode());
System.out.println("ab".hashCode() == "ba".hashCode());
- 自定义类重写equals() 和 hashCode()
import java.util.Objects;
public class Son extends Father{
private String name;
private int age;
private int sex;
public Son() {
}
public Son(String name) {
this.name = name;
}
public Son(int age) {
super(123);
this.age = age;
}
public Son(String name, int age) {
this(name);
}
public Son(String name, int age, int sex) {
this(name, age);
this.sex = sex;
}