ArrayList 按优先级排序

1 java sorting arraylist

我有一个对象列表,这些对象实际上是棋子。

每个对象都包含价格名称及其在国际象棋桌上的位置。名字K用于国王、Q王后、R车……等等。

所以我有一个ArrayList<Enemy> chesspieces. 列表没有排序,元素可能是这样的:

P,P,P,P,P,P,P,P,R,N,B,Q,K,B,N,R.
Run Code Online (Sandbox Code Playgroud)

我想创建某种prioritySort,有一个这样的列表:

K,Q, R, R, B, B, N,N,R,R P,P,P,P,P,P,P,P
Run Code Online (Sandbox Code Playgroud)

我开始做一些事情,但我看到它是如何有缺陷的,我不确定如何实现,这是我到目前为止所做的

这是我更新的 Enemy 课程



public class Enemy implements Comparable {

        public Piece name;
        public int rank;
        public int file;
        public String position;
        private int value;

        public Enemy(Piece name, int file, int rank,  String position) {
            this.name = name;
            this.rank = rank;
            this.file = file;
            this.position = position;
        }


    public int getValue(Piece name) {
        if (name.toString() == "k") value = 0;
        if (name.toString() == "Q") value = 1;
        if (name.toString() == "R") value = 2;
        if (name.toString() == "B") value = 3;
        if (name.toString() == "N") value = 4;
        if (name.toString() == "R") value = 5;
        if (name.toString() == "P") value = 6;
        System.out.println("ENMIY : " + name.toString() + " threat" + value);
        return value;
    }


    @Override
    public int compareTo(Object o) {
        if (o instanceof Enemy) {
            Enemy other = (Enemy)o;

            return this.value - other.value;
        } else {
            return 0;
        }
    }
}

Run Code Online (Sandbox Code Playgroud)

这是我的输出

Collections.sort(enemyLocation);// PPNPPPPPPRNBQKBR
Run Code Online (Sandbox Code Playgroud)

Sum*_*ngh 5

使用以下代码:

Collections.sort(YourList, YourComparator);
Run Code Online (Sandbox Code Playgroud)

创建Comparator并将您的逻辑放在int compare(T o1, T o2) 中

    Collections.sort(list, new Comparator<Piece>() {

        @Override
        public int compare(Piece o1, Piece o2) {
            // Your logic 
            //a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
            return Your-Return-Value;
        }
    });
Run Code Online (Sandbox Code Playgroud)

在这里检查几个示例Java 中的比较器接口