容易忽视但是功能灰常强大的Java API(四. 排序的集合)

四. 排序的集合

在java中,提供了一个(可能还有其它的)可以进行排序的集合对象TreeSet,它实现了SortedSet集合接口,对于普通类型的集合元素,它们默认是按照字母顺序排列的,对于复杂类型的集合元素,需要为集合对象指定比较器。看下面的例子:

public class TreeSetTest {

    private static Comparator comparator = new Comparator() {    
        public int compare(Node o1, Node o2) {     
            int diff = o1.getValue() - o2.getValue();     
            if (diff > 0) {     
                return 1;     
            } else if(diff < 0){     
                return -1;     
            } else {     
                return 0;     
            }     
        }     
    };

    public static void main(String[] args) {    
        TreeSetTest tst = new TreeSetTest();     
        SortedSet pq = new TreeSet(comparator);     
        pq.add(tst.new Node(3));     
        pq.add(tst.new Node(5));     
        pq.add(tst.new Node(2));     
        pq.add(tst.new Node(1));     
        Iterator it = pq.iterator();     
        while(it.hasNext()){     
            Node node = it.next();     
            System.out.println(node.getValue());     
        }     
    }

    public class Node {    
        private int value;

        public Node(int value) {    
            this.value = value;     
        }

        public int getValue() {    
            return value;     
        }

        public void setValue(int value) {    
            this.value = value;     
        }     
    }

}

测试结果:

1    
2     
3     
5

posted on 2011-07-01 10:48  GongTao  阅读(417)  评论(0编辑  收藏  举报

导航