- /*
- 需求:将学生对象和地址存入到Map集合中,姓名和年龄相同视为同一个学生
- */
- import java.util.*;
- class HashMapTest
- {
- public static void main(String[] args)
- {
- HashMap<Student,String> hm=new HashMap<Student,String>();
- hm.put(new Student("张三",18),"武汉");
- hm.put(new Student("李四",19),"天津");
- hm.put(new Student("王五",18),"西安");
- hm.put(new Student("赵六",18),"北京");
- hm.put(new Student("张三",18),"武汉");
- /*
- HashMap集合获取元素的第一种方式,迭代键的集合
- Set<Student> set=hm.keySet();
- Iterator<Student> it=set.iterator();
- while(it.hasNext()){
- Student stu=it.next();
- String homeTown=hm.get(stu);
- System.out.println("Student:"+stu+",homTown:"+homeTown);
- }
- */
- //HashMap集合获取元素的第二种方式,迭代映射关系
- Set<Map.Entry<Student,String>> entry=hm.entrySet();
- Iterator<Map.Entry<Student,String>> it=entry.iterator();
- while(it.hasNext()){
- Map.Entry<Student,String> me=it.next();
- Student stu=me.getKey();
- String homeTown=me.getValue();
- System.out.println(stu+"来自"+homeTown);
- }
- }
- }
- class Student implements Comparable<Student>
- {
- private String name;
- private int age;
- Student(String name,int age){
- this.name=name;
- this.age=age;
- }
- public String getName(){
- return name;
- }
- public int getAge(){
- return age;
- }
- public int hashCode(){
- return name.hashCode()+age*7;
- }
- //复写compareTo()方法,定义元素的比较方式
- public int compareTo(Student stu){
- int num=this.name.compareTo(stu.name);
- if(num==0)
- return new Integer(this.age).compareTo(stu.age);
- return num;
- }
- //自定义equals方法,判断两个Person对象是否相同
- public boolean equals(Object obj){
- if(!(obj instanceof Student))
- return false;
- Student stu=(Student)obj;
- return this.getName().equals(stu.getName())&&this.age==stu.age;
- }
- public String toString(){
- return this.name+":"+this.age;
- }
- }
复制代码
|
-
1.png
(4.41 KB, 下载次数: 8)
第一种方式结果
-
2.png
(3.2 KB, 下载次数: 6)
第二种运行结果
|