package cn.heima;
import java.util.*;
public class HashCodeTest {
public static void main(String[] args)
{
Set<Student> set = new HashSet<Student>();
Student s1 = new Student("lisi",12);
Student s2 = new Student("zhangsan",13);
Student s3 = new Student("lisi",12);
set.add(s1);
set.add(s2);
set.add(s3);
s1.age = 10;
set.remove(s1); //不加这句时打印的集合大小是2,加了这句打印的集合大小还是2,为什么删不掉呢?
System.out.println(set.size());
}
}
class Student{
int age;
String name;
Student(String name,int age)
{
this.age = age;
this.name = name;
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Student other = (Student) 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;
}
}
|