有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

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

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

我有另外两个类来扩展这个类(MoveLeft和MoveRight类)。我将这两种类型的对象添加到类型Move的列表中,然后使用集合进行排序。排序:

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) 个答案

  1. # 1 楼答案

    您必须创建Move数组,并使用派生类的混合来填充它,将其向上投射,以便像往常一样对其进行移动和排序,然后您可以使用isntanceOf和downcast检查实际的类

  2. # 2 楼答案

    这确实是一个很长的评论,而不是一个答案

    我写了一个简单的测试程序,它看起来排序正确。输出是[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);
      }
    
    }