首页 > 解决方案 > ArrayList 按优先级排序

问题描述

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

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

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

P,P,P,P,P,P,P,P,R,N,B,Q,K,B,N,R.

我想创建某种prioritySort,以获得这样的列表:

K,Q, R, R, B, B, N,N,R,R P,P,P,P,P,P,P,P

我开始做某事,但我看到它有缺陷,我不知道如何实现它,这是我到目前为止所做的

这是我更新的敌人课程



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;
        }
    }
}

这是我的输出

Collections.sort(enemyLocation);// PPNPPPPPPRNBQKBR

标签: javasortingarraylist

解决方案


使用以下代码:

Collections.sort(YourList, YourComparator);

创建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;
        }
    });

在此处查看一些示例Java 中的比较器接口


推荐阅读