Java对任何对象数组进行排序

时间:2013-03-15 13:21:53

标签: java sorting collections

我已经定义了一个抽象类,如下所示:

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

但是,列表按单元格而不是按重量排序。

是不是可以在同一种类中混合不同的子类实例?

注意:我在子类构造函数中设置了一个唯一的权重值。

2 个答案:

答案 0 :(得分:0)

你必须创建Move数组,使用派生类的混合将其向上转换为Move并像往常一样对其进行排序,然后你可以使用isntanceOf和downcast检查你的实际类。

答案 1 :(得分:0)

这是一个非常长的评论,而不是答案。

我写了一个简单的测试程序,看起来排序正确。输出为[Move [cell=10, weight=1], Move [cell=1, weight=100]],既不是我添加元素的顺序,也不是升序单元格顺序,而是递增权重顺序。

我注意到你有两个相同类型的构造函数参数。我建议非常仔细地检查他们是否没有切换。如果这不是问题,我建议尝试修改我的测试程序,使其更类似于真实代码,直到它再现问题。这是我的测试程序:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Test {
  public static void main(String[] args) {
    List<Move> list = new ArrayList<Move>();
    list.add(new MoveRight(1, 100));
    list.add(new MoveLeft(10, 1));
    Collections.sort(list);
    System.out.println(list);
  }
}

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

  @Override
  public String toString() {
    return "Move [cell=" + cell + ", weight=" + weight + "]";
  }
}

class MoveLeft extends Move {

  protected MoveLeft(int cell, int weight) {
    super(cell, weight);
  }

}

class MoveRight extends Move {

  protected MoveRight(int cell, int weight) {
    super(cell, weight);
  }

}