修改如下,有什么问题存在还可继续探讨。有错误和有点不适合的地方已经用注释标注。最后附上一张hash表的结构图(来自动力节点)。- package com.sergio.Thread;
- /**
- * @ClassName: Test06
- * @Description: TODO(这里用一句话描述这个类的作用)
- * @author Sergio Han
- * @date 2013-8-11 下午4:16:06
- *
- */
- import java.util.*;
- class Student implements Comparable<Student> {
- private String name;
- private int age;
- // Student(String name, int age) {
- // this.name = name;
- // this.age = age;
- // }
- //此处也是写错
- Student(String name, int age)
- {
- this.name = name;
- this.age = age;
- }
- // public int compareTo(Student s) {
- // int num = new Integer(this.age).compareTo(s.name);
- // return num;
- // }
-
- //此处写错了
- public int compareTo(Student s)
- {
- int num = new Integer(this.age).compareTo(s.age);
- return num;
- }
- public int hashCode() {
- //return name.hashCode() + age * 20;
- //此处写法的有点问题,估计是你还没明白hash表的结构。hahscode()这个相当于数组中的下标了,以那个参数选取hash值来悬挂数组中的位置
- return new String(name).hashCode();
- }
- // public boolean equals(Object obj)
- // {
- // if (!obj instanceof Student)
- // {
- // throw new ClassCastException("leixingcuowu");
- // Student s = (Student)obj;
- // return this.name.equals(s.name) && this.age==s.age;
- // }
- // }
-
- //上面的写法有点问题,下面写法可参考。比较的变量是name,是age,自己修改即可
- public boolean equals(Object o)
- {
- if(o == this)
- {
- return true;
- }
- if(o instanceof Student)
- {
- Student s = (Student)o;
- if(this.name == s.name)
- {
- return true;
- }
- }
- return false;
- }
-
-
- public String getName() {
- return name;
- }
- public int getAge() {
- return age;
- }
- public String toString() {
- return name + ":" + age;
- }
- }
- class Test06 {
- public static void main(String[] args) {
- //后面的HashMap没有写全
- // HashMap<Student, String> hm = new Hash<Student, String>();
- HashMap<Student, String> hm = new HashMap<Student, String>();
- hm.put(new Student("lisi1", 21), "beijing");
- hm.put(new Student("lisi2", 22), "beijing");
- hm.put(new Student("lisi3", 23), "beijing");
- hm.put(new Student("lisi4", 24), "beijing");
- Set<Student> keySet = hm.keySet();
- Iterator<Student> it = keySet.iterator();
- while (it.hasNext()) {
- Student stu = it.next();
- String addr = hm.get(stu);
- System.out.println(stu + "---" + addr);
- }
- }
- }
复制代码
|