| import java.util.*; class Student implements Comparable<Student>//2实现Comparable接口,让对象具有比较性,类型是Student
 {
 private String name;//1 描述学生,进行set,get方法
 private int age;
 Student(String name,int age)
 {
 this.name=name;
 this.age=age;
 
 }
 public void setName(String name)
 {
 this.name=name;
 }
 public void setAge(int age)
 {
 this.age=age;
 
 }
 public String getName()
 {
 return name;
 }
 public int getAge()
 {
 return age;
 }
 public int compareTo(Student s)//调用接口中比较方法
 {
 int num=new Integer(this.age).compareTo(new Integer (s.age));
 if(num==0)
 return this.name.compareTo(s.name);
 return num;
 }
 public int hashCode()//3 复写hashcode方法,确定位置
 {
 return name.hashCode()+age*20;//返回名字的哈希值
 
 }
 public boolean equals(Object obj)
 {
 if (!(obj instanceof Student))
 throw new ClassCastException("类型不匹配");//一定要抛出这种错误吗?????
 Student s=(Student)obj;//这里还运用了转型 ,怎么不能应用泛型啊????
 
 return this.name.equals(s.name)&&this.age==s.age;
 
 
 }
 
 }
 
 
 
 
 class MapTest
 {
 public static void main(String[] args)
 {
 HashMap<Student,String> hm = new HashMap<Student,String>();//建立集合
 hm.put(new Student("lisi1",21),"beijing");//添加元素,student定义为key,地址为value,为什么要这么设定那??????
 hm.put(new Student("lisi2",22),"jing");
 hm.put(new Student("lisi3",23),"bei");
 hm.put(new Student("lisi4",24),"beng");
 //第一种取出方式KeySet
 Set<Student>keySet=hm.keySet();//子类获取Set父类的方法
 
 Iterator<Student> it=keySet.iterator();//获取迭代器
 
 while (it.hasNext())
 {
 Student stu =it.next();//返回是student类型的。用stu记录
 String addr=hm.get(stu);//value=get(key)
 System.out.println(stu+"***"+addr);
 }
 
 
 
 System.out.println("Hello World!");
 }
 }
 打印怎么出错了呢????
 Student@62363cc***bei
 Student@62363a2***beijing
 Student@62363e1***beng
 Student@62363b7***jing
 Hello World!
 怎么都是哈希值啊,求解啊
 
 |