如下我已经定义了一个抽象类对象中的任意数组:爪哇排序
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的)。我想补充这两种类型的对象类型移动的一个列表,然后排序使用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? – 2013-03-15 13:24:51
不,他们没有。他们应该吗? – 2013-03-15 13:25:36
不......这将是您见过的行为的一种解释。 – 2013-03-15 13:26:04