【发布时间】:2020-01-27 05:12:14
【问题描述】:
我有一个对象列表,这些对象实际上是棋子。
每个对象都包含价格名称及其在棋盘上的位置。
名字是K代表国王,Q代表女王,R代表车……等等。
所以我有一个ArrayList<Enemy> chesspieces。列表未排序,元素可能是这样的:
P,P,P,P,P,P,P,P,R,N,B,Q,K,B,N,R.
我想创建某种优先级排序,以获得这样的列表:
K,Q, R, R, B, B, N,N,R,R P,P,P,P,P,P,P,P
我开始做某事,但我发现它有缺陷,我不知道如何实现它,这是我到目前为止所做的
这是我更新的 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;
}
}
}
这是我的输出
Collections.sort(enemyLocation);// PPNPPPPPPRNBQKBR
【问题讨论】:
-
初始化逮捕将解决您的第一个问题。 ArrayList
sortedThreat = new ArrayList(); -
不要在 java 中将
==与字符串一起使用。使用equals()。 stackoverflow.com/questions/7520432 -
什么是
Enemy和Piece? -
编码
getValue()的更简单方法是value = "kQRBNRP".indexOf(name.toString());。