用keySet和entrySet取出元素

来源:互联网 发布:淘宝首页装修素材下载 编辑:程序博客网 时间:2024/06/05 00:36

用keySet和entrySet取出元素

import java.util.*;public class MapTest {    public static void sop(Object obj) {        System.out.println(obj);    }    public static void main(String[] args) {        Map<Student, String> hs = new TreeMap<Student, String>();        hs.put(new Student("zs005", 25), "shanghai");        hs.put(new Student("zs005", 25), "beihai");        hs.put(new Student("zs002", 64), "beijing");        hs.put(new Student("zs010", 26), "nanjing");        // 方式一:keySet        Set<Student> ss = hs.keySet();        for(Iterator<Student> it = ss.iterator(); it.hasNext(); ) {            Student s = it.next();            sop("Info: " + s + ", Addr: " + hs.get(s));        }        // 方式二:entrySet        Set<Map.Entry<Student, String>> me = hs.entrySet();        for(Iterator<Map.Entry<Student, String>> it = me.iterator(); it.hasNext(); ) {            Map.Entry<Student, String> s = it.next();            sop("Info2: " + s.getKey() + ", Addr2: " + s.getValue());        }    }}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 this.name;    }    public int getAge() {        return this.age;    }    public String toString() {        return this.name + ", " + this.age;    }    public int hashCode() {        return this.name.hashCode() + this.age*34;    }    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;    }    public int compareTo(Student s) {        int num = this.name.compareTo(s.name);        if(num == 0)            return new Integer(this.age).compareTo(new Integer(s.age));        return num;    }}

输出结果

Info: zs002, 64, Addr: beijingInfo: zs005, 25, Addr: beihaiInfo: zs010, 26, Addr: nanjingInfo2: zs002, 64, Addr2: beijingInfo2: zs005, 25, Addr2: beihaiInfo2: zs010, 26, Addr2: nanjing
0 0
原创粉丝点击