TreeMap的使用

TreeMap的使用

TreeMap与TreeSet类似,也需要通过存储元素的对象类型实现Comparable接口进而重写compareTo方法来确定排序规则,存储结构也是红黑树,如果要在实例化TreeMap对象的时候确定排序规则,就实现Comparator接口(通过匿名内部类的方式来实现),Comparator实际上就是一个排序规则定制器

/**
 * 存储结构:红黑树
 */
public class Test {
    public static void main(String[] args) {
        //创建集合
//        TreeMap treeMap = new TreeMap<>(new Comparator() {
//            @Override
//            public int compare(Student o1, Student o2) {
//                int n1 = o1.getName().compareTo(o2.getName());
//                int n2 = o1.getAge()-o2.getAge();
//                return n1==0?n2:n1;
//            }
//        });
        TreeMap<Student,String> treeMap = new TreeMap<Student,String>();

        //1添加元素
        Student s1 = new Student("学生一", 28);
        Student s2 = new Student("学生二", 50);
        Student s3 = new Student("学生三", 21);
        Student s4 = new Student("学生四", 24);
        treeMap.put(s1,"上海");
        treeMap.put(s2,"广东");
        treeMap.put(s3,"深圳");
        treeMap.put(s4,"龙南");
        System.out.println(treeMap.size());//4
        System.out.println(treeMap.toString());

        //2删除元素
        //treeMap.remove(new Student("学生一", 28));//重写equals与hashcode方法
       // System.out.println(treeMap.size());//3

        //3遍历
        //3.1增强for循环
        System.out.println("============keySet()====增强for循环==========");
        Set<Student> students = treeMap.keySet();
        for (Student s:students){
            System.out.println(s+"-----"+treeMap.get(s));
        }
        //3.2迭代器
        System.out.println("============entrySet()====迭代器==========");
        Iterator<Student> iterator = students.iterator();
        while (iterator.hasNext()){
            Student next = iterator.next();
            System.out.println(next+"-------"+treeMap.get(next));
        }
        Set<Map.Entry<Student, String>> entries = treeMap.entrySet();
        System.out.println("============entrySet()====增强for循环==========");
        for(Map.Entry<Student, String> entry:entries){
            System.out.println(entry.getKey()+"----------"+entry.getValue());
        }
        System.out.println("============entrySet()====迭代器==========");
        Iterator<Map.Entry<Student, String>> iterator1 = entries.iterator();
        while (iterator1.hasNext()){
            Map.Entry<Student, String> next = iterator1.next();
            System.out.println(next.getKey()+"------"+next.getValue());
        }

    }
}

你可能感兴趣的:(JavaSE,hashmap,iterator,链表,TreeMap,红黑树)