java - 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
解决方案
使用以下代码:
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 中的比较器接口
推荐阅读
- c++ - 调用 mongocxx::instance 返回“mongoc: 无法初始化 OpenSSL”
- c# - 将东/北转换为纬度 Lng
- ruby-on-rails - Ruby on Rails 扩展 gem 的类并更改其继承类
- php - 使用干预在 laravel 中上传图像
- javascript - 角度6中多个数组中的公共元素
- c# - WPF动画对象碰撞检测,对象不在交叉位置显示
- python - 在数据框中,我有一个这样的列。9(05) X(5) X(15) X(15) X(15) S9(07) S9(2)V9(2) 我想把它们分成四个不同的列
- firebase - 每当记录进入firestore数据库时,我们可以自动向用户发送推送通知吗?
- javascript - 追加时访问父数据
- c# - 通过 C# 格式化 HTML