2016-04-29 109 views
-1

我有一个名为DrawingObject的抽象类,它被四个子类扩展:Point,Line,FreeFormLine和Circle。 DrawingObject实现可比性,我已经定义了compareTo方法看起来像这样比较不同的对象

public int compareTo(DrawingObject object) 
{ 
    if(object instanceof Point && this instanceof Point) 
    { 
     //determine which has a higher value 
     return 0; 
    } 
    else if(object instanceof Point && this instanceof Line) 
     return 1; 
    else if(object instanceof Point && this instanceof FreeFormLine) 
     return 1; 
    else if(object instanceof Point && this instanceof Circle) 
     return 1; 

    else if(object instanceof Line && this instanceof Point) 
     return -1; 
    else if(object instanceof Line && this instanceof Line) 
    { 
     //determine which has a higher value 
     return 0; 
    } 
    else if(object instanceof Line && this instanceof FreeFormLine) 
     return 1; 
    else if(object instanceof Line && this instanceof Circle) 
     return 1; 

    else if(object instanceof FreeFormLine && this instanceof Point) 
     return -1; 
    else if(object instanceof FreeFormLine && this instanceof Line) 
     return -1; 
    else if(object instanceof FreeFormLine && this instanceof FreeFormLine) 
    { 
     //determine which has a higher value 
     return 0; 
    } 
    else if(object instanceof FreeFormLine && this instanceof Circle) 
     return 1; 

    else if(object instanceof Circle && this instanceof Point) 
     return -1; 
    else if(object instanceof Circle && this instanceof Line) 
     return -1; 
    else if(object instanceof Circle && this instanceof FreeFormLine) 
     return -1; 
    else if(object instanceof Circle && this instanceof Circle) 
    { 
     //determine which has a higher value 
     return 0; 
    } 

    return 0; 
} 

现在,我有这个,我想用价值来扩展代码排序。我很困惑如何去做这件事。例如Point有两个实例字段,double x和double y。我很困惑要排序。我也困惑于其他类型的对象以及如何对它们进行排序。每个类都有一个equals方法,它在DrawingObject中声明为抽象,但在每个子类中实现。

以下是每个班级中的字段说明: Point有两个双字段,x和y。这些表示该点的笛卡尔坐标网格上的坐标。 线有两个点字段,p1和p2。这些代表了该线的起点和终点。 FreeFormLine有一个ArrayList字段,分。这代表了沿线的所有点。 圆有一个点域,中心和一个双半径域。这些代表圆的中心点和半径。

总之,当有多个字段需要评估时,如何确定哪个对象具有更多或更少的价值?

编辑: 做这种排序的目的是让我能够通过使用二进制搜索的DrawingObjects数组有效地进行搜索。

+0

这是你必须回答的问题。它太宽泛 - 例如它可能基于线长(或圆半径)或线的最左点(假设为2D)。没有普遍的答案。 – John3136

+0

我意识到这一点。我更多的是寻求建议,而不是具体的答案。 – Jacob

+0

“排列形状列表”甚至意味着什么?我们如何知道你为什么这样做?没有更多的信息,就不能给出明智的答案。 – John3136

回答

1

您尝试解决的问题比ut好得多,因为您正在尝试构建一个双重调度方法,即针对两个对象虚拟的方法。

有办法可以做到这一点,例如,使用访问者模式,但如果你在跨不同类别建立固定顺序方面会很好(例如,一个点总是小于一个矩形,一个矩形小于线等),你可以让你的代码非常一致通过在基类保护的方法,它返回的“排序”的类:

protected abstract int sortOrder(); 

点会返回0,矩形将返回1,行将返回2,依此类推。现在,您的比较方法可以在两边调用sortOrder(),并且如果排序ordrrs不相同,则可以决定哪一个小于另一个。

如果排序顺序相同,那么类是相同的。在每个类中实现类比,并在类相同时将该调用转发给特定于类的比较方法。

只要对同一个类进行比较,您可以决定属性之间的任意排序 - 比方说y之前的x,宽度之前的高度等等。只要您对应用规则一致,您的排序将会很好。