1. 程式人生 > >comparator介面與Comparable介面的使用

comparator介面與Comparable介面的使用

先引用別人的解釋: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);