comparator接口与Comparable接口的使用

来源:互联网 发布:python生成随机50个数 编辑:程序博客网 时间:2024/06/05 09:59

先引用别人的解释:http://www.cnblogs.com/sunflower627/p/3158042.html

自己还没有好好了解这一部分,所以不太会使用。目前使用过的两个地方有:

  • Comparable
    private class Node implements Comparable<Node> {        private Board board;        private Node pre;        private int step;        private boolean isTwin;        public Node(Board board, Node pre, int step, boolean isTwin) {            this.board = board;            this.pre = pre;            this.step = step;            this.isTwin = isTwin;        }        public int compareTo(Node that) {            int predict1 = this.step + this.board.manhattan();            int predict2 = that.step + that.board.manhattan();            if (predict1 < predict2)                return -1;            if (predict1 > predict2)                return 1;            return 0;        }


  • Comparator(使优先队列从大到小排列)

        Comparator<Integer> inverseSort;        inverseSort = new Comparator<Integer>() {            @Override            public int compare(Integer o1, Integer o2) {                // TODO Auto-generated method stub                return o2 - o1;            }        };        PriorityQueue<Integer> qh = new PriorityQueue<Integer>();        PriorityQueue<Integer> ql = new PriorityQueue<Integer>(1, inverseSort);



原创粉丝点击