重写JAVA中的hashCode()方法
▪️测试56.java
import java.util.*;
public class Test56 {
public static void main(String[] args) {
Set<Hare56> hare = new HashSet<Hare56>();
Hare56 h1 = new Hare56();
Hare56 h2 = new Hare56();
Hare56 h3 = new Hare56();
h1.name = "野うさぎ";
h2.name = "野うさぎ2";
h3.name = "野うさぎ3";
h1.item = "にんじん";
h2.item = "にんじん";
h3.item = "にんじん";
h1.item2 = "レタス";
h2.item2 = "レタス";
h3.item2 = "レタス";
hare.add(h1);
hare.add(h2);
hare.add(h3);
System.out.println(hare.size());
hare.remove(h2);
System.out.println(hare.size());
}
}
Hare56.java的原文是:
public class Hare56 {
public String name;
public int hp;
public String item;
public String item2;
public boolean equals(Object o) {
if (this.name == o && this.item == o && this.item2 == o) {
return true;
}
return false;
}
public int hashCode() {
int result = 35;
result = result * 31 + name.hashCode();
result = result * 31 + item.hashCode();
result = result * 31 + item2.hashCode();
return result;
}
}
▪️Test56.java 的执行结果是
3
2