黑马程序员技术交流社区
标题:
基础视频day14练习3
[打印本页]
作者:
不怕黑人
时间:
2015-7-24 15:00
标题:
基础视频day14练习3
/**
* 题目:用hashset存储人(具有年龄,姓名属性)。
* 思路:hashset底层结构是哈希表,其保证元素唯一性的方法通过元素的hashcode()和equals()方法来完成。
* 注意:对于判断元素是否存在,以及删除等操作也是通过元素的hashcode()和equals()方法来完成。
*@author XiaLei
*/
public class Day14Tes8t {
public static void main(String[] args) {
HashSet<Student> hs = new HashSet<Student>();
hs.add(new Student("zha01",2));
hs.add(new Student("zha02",2));
hs.add(new Student("zha03",4));
hs.add(new Student("zha01",2));
for (Iterator<Student> it = hs.iterator(); it.hasNext(); ){
System.out.println(it.next());
}
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
super();
this.name = name;
this.age = age;
}
//覆盖hashCode方法
public int hashCode(){
return name.hashCode()+age*39;//*39是习惯,如果直接*age要考虑不要超过int类型范围。
}
//覆盖equals方法
public boolean equals(Object obj){
if (!(obj instanceof Student))
return false;
Student s = (Student)obj;
return this.name.equals(s.name) && this.age == s.age;
}
public String toString(){
return "name="+this.name+" age="+this.age;
}
}
复制代码
作者:
eayonh
时间:
2015-7-24 16:18
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2