您的位置:首页 > 编程语言 > Java开发

java的hashCode和equals函数在HashMap容器中的作用

2014-12-08 09:53 453 查看
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();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: