黑马程序员技术交流社区

标题: treeMap如何根据值来排序啊 [打印本页]

作者: 朱皓    时间: 2012-2-23 14:49
标题: treeMap如何根据值来排序啊
treeMap如何根据值来排序啊
作者: foxpeter    时间: 2012-2-23 15:04
    public V put(K key, V value) {
        Entry<K,V> t = root;
        if (t == null) {
            compare(key, key); // type (and possibly null) check

            root = new Entry<>(key, value, null);
            size = 1;
            modCount++;
            return null;
        }
        int cmp;
        Entry<K,V> parent;
        // split comparator and comparable paths
        Comparator<? super K> cpr = comparator;
        if (cpr != null) {
            do {
                parent = t;
                cmp = cpr.compare(key, t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        else {
            if (key == null)
                throw new NullPointerException();
            Comparable<? super K> k = (Comparable<? super K>) key;
            do {
                parent = t;
                cmp = k.compareTo(t.key);
                if (cmp < 0)
                    t = t.left;
                else if (cmp > 0)
                    t = t.right;
                else
                    return t.setValue(value);
            } while (t != null);
        }
        Entry<K,V> e = new Entry<>(key, value, parent);
        if (cmp < 0)
            parent.left = e;
        else
            parent.right = e;
        fixAfterInsertion(e);
        size++;
        modCount++;
        return null;
    }

应该是根据 comparator或者comparable接口来实现排序的
作者: 朱皓    时间: 2012-2-23 15:12
看不懂,晕了

作者: 陈伟    时间: 2012-2-23 16:30
TreeMap的底层数据结构是二叉树,不用重复进行比较,提高了排序的效率,它实现排序的方式有两种,第一种:对象本身具有比较性,例如字符串,自身具有比较性,如果是自定义的类,那么需要实现Comparable接口,复写compareTo()方法。第二种:就是让集合本身具有比较性,定义一个比较器类实现Comparator接口,复写compare()方法,然后将这个比较器对象作为参数传递给TreeMap的构造函数中,让集合一初始化就具有比较性;
作者: 李会启    时间: 2012-2-23 16:59
ArrayList<Integer> list = new ArrayList<Integer>();
        TreeMap<Integer, Integer> tm = Calculate.tjj(0);
        // 倒序
        NavigableSet<Integer> descendingKeySet = tm.descendingKeySet();
        // 顺序
        // Set testset = tm.keySet();
        Iterator<Integer> it = descendingKeySet.iterator();
        while (it.hasNext()) {
            int key = it.next();
            System.out.println("key:" + key);
            int paramObject = tm.get(key);
            System.out.println(paramObject);
            list.add(paramObject);
        }






欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2