黑马程序员技术交流社区

标题: 基础视频day14练习3 [打印本页]

作者: 不怕黑人    时间: 2015-7-24 15:00
标题: 基础视频day14练习3
  1. /**
  2. * 题目:用hashset存储人(具有年龄,姓名属性)。
  3. * 思路:hashset底层结构是哈希表,其保证元素唯一性的方法通过元素的hashcode()和equals()方法来完成。
  4. * 注意:对于判断元素是否存在,以及删除等操作也是通过元素的hashcode()和equals()方法来完成。
  5. *@author XiaLei
  6. */
  7. public class Day14Tes8t {

  8.         public static void main(String[] args) {

  9.                 HashSet<Student> hs = new HashSet<Student>();
  10.                 hs.add(new Student("zha01",2));
  11.                 hs.add(new Student("zha02",2));
  12.                 hs.add(new Student("zha03",4));
  13.                 hs.add(new Student("zha01",2));
  14.                 for (Iterator<Student> it = hs.iterator(); it.hasNext();  ){
  15.                         System.out.println(it.next());
  16.                 }
  17.         }

  18. }
  19. class Student{
  20.         private String name;
  21.         private int age;
  22.         public Student(String name, int age) {
  23.                 super();
  24.                 this.name = name;
  25.                 this.age = age;
  26.         }
  27.         //覆盖hashCode方法
  28.         public int hashCode(){
  29.                 return name.hashCode()+age*39;//*39是习惯,如果直接*age要考虑不要超过int类型范围。
  30.         }
  31.         //覆盖equals方法
  32.         public boolean equals(Object obj){
  33.                 if (!(obj instanceof Student))
  34.                         return false;
  35.                 Student s = (Student)obj;
  36.                 return this.name.equals(s.name) && this.age == s.age;
  37.         }
  38.         public String toString(){
  39.                 return "name="+this.name+"  age="+this.age;
  40.         }
  41. }
复制代码

作者: eayonh    时间: 2015-7-24 16:18





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2