我有一个名为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数组有效地进行搜索。
这是你必须回答的问题。它太宽泛 - 例如它可能基于线长(或圆半径)或线的最左点(假设为2D)。没有普遍的答案。 – John3136
我意识到这一点。我更多的是寻求建议,而不是具体的答案。 – Jacob
“排列形状列表”甚至意味着什么?我们如何知道你为什么这样做?没有更多的信息,就不能给出明智的答案。 – John3136