TreeMap集合存放自定义对象

2017-02-14  本文已影响71人  李霖神谷
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;

class People implements Comparable {
    private String name;
    private int age;

    public People(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    @Override
    public String toString() {
        return "People [name=" + name + ", age=" + age + "]";
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public int compareTo(Object o) {
        // TODO Auto-generated method stub
        People p = (People) o;
        return this.age - p.age;
    }
}

public class TreeMapDemo {
    public static void main(String[] args) {
        TreeMap tm = new TreeMap();
        tm.put(new People("撒哈拉沙漠", 21), "lishuai");
        tm.put(new People("耶路撒冷", 22), "liqian");
        tm.put(new People("普罗旺斯", 23), "liming");
        tm.put(new People("撒哈拉沙漠", 22), "lishuai");
        Set s = tm.entrySet();
        for (Iterator iterator = s.iterator(); iterator.hasNext();) {
            Object o = iterator.next();
            Map.Entry e = (Map.Entry) o;
            Object key = e.getKey();
            Object value = e.getValue();
            System.out.println(key + "====" + value);
        }
    }
}

TreeMap的底层是红黑树结构,因此自定义类它需要继承comparable,然后通过compareTo方法来自定义比较方法。其实这都是对以上学过的东西进行复习。

上一篇下一篇

猜你喜欢

热点阅读