本帖最后由 ぺsimon☆ 于 2013-4-28 17:42 编辑
- /*
- 需求:把学生和其所属户籍存到HashMap集合中
- 因为学生不唯一的,户籍可以相同,所以在HashMap中以学生为键,户籍为值
- 学生类中,姓名和年龄相同视为一个学生
- */
- import java.util.*;
- class Student implements Comparable<Student>//实现Comparable比较器
- {
- private String name;
- private int age;
- Student(String name,int age) //构造函数
- {
- this.name=name;
- this.age=age;
- }
- public void setName(String name) //设置名字
- {
- this.name=name;
- }
- public String getName() //获取获取名字
- {
- return name;
- }
- public void setAge(int age)//设置年龄
- {
- this.age=age;
- }
- public int getAge()//获取年龄
- {
- return age;
- }
- public int compareTo(Student obj) //覆盖compareTo方法
- {
- if(!(obj instanceof Student))
- throw new RuntimeException();
- Student s=(Student)obj;
- 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() //覆盖hashCode方法
- {
- return name.hashCode()+age*6;
- }
- public boolean equals(Student obj) //覆盖equals方法
- {
- if(!(obj instanceof Student))
- return false;
- Student s=(Student)obj;
- return this.name.equals(s.name)&&this.age==s.age;
- }
- //***覆盖toString方法 ,这里不懂...为什么把toString()方法覆盖之后,程序打印
- 的Student对象是:name+":"+age ,不覆盖toSring方法打印出来的Student是一个地
- 址值,而这个地址值又是怎么来的呢?
- public String toString()
- {
- return name+":"+age;
- }
- }
- class HashMapStudent
- {
- public static void main(String[] args)
- {
- //创建一个容器
- HashMap<Student,String> hs=new HashMap<Student,String>();
- hs.put(new Student("zhangsan",01),"guangzhou01");
- hs.put(new Student("zhangsan",02),"guangzhou02");
- hs.put(new Student("zhangsan",03),"guangzhou03");
- hs.put(new Student("zhangsan",04),"guangzhou04");
- hs.put(new Student("zhangsan",05),"guangzhou05");
- //得到映射关系
- Set<Map.Entry<Student,String>> s=hs.entrySet();
- //得到迭代器
- Iterator<Map.Entry<Student,String>> it=s.iterator();
- //循环输出每一个键值对
- while(it.hasNext())
- {
- Map.Entry<Student,String> me=it.next();
- System.out.println(me.getKey()+"="+me.getValue());
- }
- /*
- Set<Student> s=hs.keySet();
- Iterator<Student> it=s.iterator();
- while(it.hasNext())
- {
- Student s1=it.next();
- String s2=hs.get(s1);
- System.out.println(s1+"="+s2);
-
- }
- */
- }
- }
复制代码 |