2013-03-15 184 views
0

如下我已经定义了一个抽象类对象中的任意数组:爪哇排序

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

然而,该列表进行排序,通过细胞代替按重量计。

不可能在同一类中混合不同的子类实例吗?

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

+0

做的子类重写compareTo? – 2013-03-15 13:24:51

+0

不,他们没有。他们应该吗? – 2013-03-15 13:25:36

+0

不......这将是您见过的行为的一种解释。 – 2013-03-15 13:26:04

回答

0

您必须创建一个Move类型的数组,然后将它与派生类混合使用,然后像往常一样对它进行移动和排序,然后可以使用isntanceOf和downcast检查实际的类。

+0

不需要转换:Collections.sort()方法不需要该转换。在这种情况下,它将看到对象实现Comparable并调用compareTo()方法,而不管数组类型或保存实例的引用类型。 – 2013-03-15 13:32:49

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

} 
+0

是否做到了这一点,我也确保每个重量值都是唯一的。它仍然按单元格排序对象 – 2013-03-15 13:50:57

+0

@ Ivan-MarkDebono在这种情况下,我认为你最好的方法是在[SSCCE](http://sscce.org)上工作,可以通过添加到我的测试程序或通过剥离你的真实代码。 – 2013-03-15 13:57:47