代码如下:
import java.util.*;
public class Hacode {
public static void main(String[] args) {
HashSet hs=new HashSet();
Cat a1=new Cat("aaa",1);
Cat a2=new Cat("aaa",1);
Cat a3=new Cat("bbb",2);
Cat a4=new Cat("bbb",2);
hs.add(a1);
hs.add(a2);
hs.add(a3);
hs.add(a4);
hs.add(a1);
System.out.println(hs.size());
a1.age=22;
hs.remove(a2);
System.out.println(hs.size());
}
}
class Cat {
String name;
int age;
public Cat(String n,int a){
name=n;
age=a;
}
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + age;
result = PRIME * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Cat other = (Cat) obj;
if (age != other.age)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
}
为什么明明已经把a1给remove了还是输出hs的size是2呢?我只知道这与hashcode有关系,但是真的没彻底搞明白。请哪位热心高人给予详细解答呢?谢谢啊