java的hashCode跟equals函数在HashMap容器中的作用
java的任意一个Object都有两个可以重写的函数,hashCode()和equals()。hashCode可用于产生HashMap容器中Object对应的key,而equals用于判断Object相不相等。
曾经项目中遇到一个需求,抽象出来,就是统计名字相同的学生的人数,并打印相应人数的学号信息。当时就是用到了上述两个特性实现的。
public class Student{
int id;
String name;
boolean gender;
public Student(int i, String n, boolean g)
{
id = i;
name = n;
gender = g;
}
public int hashCode()
{
return name.hashCode();
}
public boolean equals(Object st)
{
return st.name.equals((Student)st.name);
}
}
public class test
{
private static HashMap<Student, Integer> map = new HashMap<Student, Integer>();
private static void appendStudent(Student st)
{
if (map.containsKey(st))
map.put(st, map.get(st) + 1);
else
map.put(st, 1);
}
private static void printMap()
{
for (Map.Entry<Student, Integer> e : map.entrySet())
{
System.out.println(e.getKey() + ":" + e.getValue());
}
}
public static void main(String[] args)
{
appendStudent(new Student(1, "wwx", true));
appendStudent(new Student(2, "wwx", true));
appendStudent(new Student(3, "wwx", true));
printMap();
}
}