【发布时间】:2013-03-15 13:21:53
【问题描述】:
我已经定义了一个抽象类如下:
public abstract class Move implements Comparable<Move> {
protected int cell;
protected int weight;
public int getWeight()
{
return this.weight;
}
public void setWeight(int value)
{
this.weight = value;
}
protected Move(int cell)
{
this.cell = cell;
this.weight = 0;
}
protected Move(int cell, int weight)
{
this.cell = cell;
this.weight = weight;
}
@Override
public int compareTo(Move m)
{
return this.weight - m.weight;
}
我还有另外 2 个类扩展了这个类(分类为 MoveLeft 和 MoveRight)。我将这两种类型的对象都添加到 Move 类型的 List 中,然后使用 Collections.sort 进行排序:
List<Move> moves = new ArrayList<Move>(someSize);
moves.add(new MoveLeft(cell1));
moves.add(new MoveRight(cell2));
moves.add(new MoveRight(cell3));
moves.add(new MoveLeft(cell4));
Collections.sort(moves);
但是,列表是按单元格而不是按重量排序的。
不能在同一个排序中混合不同的子类实例吗?
注意:我在子类构造函数中为权重设置了一个唯一值。
【问题讨论】:
-
子类是否覆盖 compareTo?
-
不是所有的权重值都是0,因为你只使用构造函数设置cell-value而不使用setWeight()?
-
在我看来,你所有的权重都是 0,所以排序顺序是任意的......(似乎@ghdalum 也注意到了,早 2 秒 ;-))
-
@Heuster 第二名只是第一个失败者:)
-
@Heuster Collections.sort 用于引用是稳定的,因此排序顺序不是任意的。如果所有 compareTo 调用都返回 0,则保留原始顺序。
标签: java sorting collections