Java 如何根据对象在直线上的位置进行比较
我正在尝试编写一个比较方法来实现这一点Java 如何根据对象在直线上的位置进行比较,java,Java,我正在尝试编写一个比较方法来实现这一点 // If a and b lie on the same horizontal line, // then a < b when a is to the left of b // Otherwise, a < b when a is below b }无论a和b是什么类型,都需要一个class属性来进行比较。一旦你开始更具体地思考,这很容易 a和b的类型是什么?if(a.y==b.y){ if (a.y == b.y) {
// If a and b lie on the same horizontal line,
// then a < b when a is to the left of b
// Otherwise, a < b when a is below b
}无论a和b是什么类型,都需要一个class属性来进行比较。一旦你开始更具体地思考,这很容易 a和b的类型是什么?
if(a.y==b.y){
if (a.y == b.y) {
return a.x < b.x;
} else {
return a.y < b.y;
}
返回a.x
从文本中,听起来像a
和b
是笛卡尔坐标(每个坐标都有一个x和一个y值)。你有代表坐标的类吗?如果不在同一条水平线上,您应该创建一个,比较方法应该取该类的两个实例,您可以使用它们的x和y值来确定它们是在同一条水平线上,还是在另一条水平线上的左边。在java中实现比较方法的一种方法是
它只有一个方法int compareTo(to)
。此方法将此对象(调用方法的对象)与指定对象(b)进行比较。当此对象小于、等于或大于指定对象时,返回负整数、零或正整数
假设对象是Pseudo类(因为它只是伪代码),那么compare方法应该如下所示
class Pseudo implements Comparable<Pseudo> {
@Override
int compareTo(Pseudo b) {
if (this and b lie on the same horizontal line) {
if (this is to the left of b) {
return -1;
} else {
return 1;
}
} else {
if (this is to the below of b) {
return -1;
} else {
return 1;
}
}
}
}
类伪实现{
@凌驾
整数比较(伪b){
如果(这和b位于同一水平线上){
如果(在b的左边){
返回-1;
}否则{
返回1;
}
}否则{
如果(这是b的以下部分){
返回-1;
}否则{
返回1;
}
}
}
}
你是说喜欢吗
class Point implements Comparable<Point> {
double x,y;
public int compareTo(Point b) {
// If a and b lie on the same horizontal line,
if (y == b.y)
// then a < b when a is to the left of b
return x < b.x ? -1 : x > b.x ? +1 : 0;
// Otherwise, a < b when a is below b
return y < b.y ? -1 : y > b.y ? +1 : 0;
}
}
类点实现可比较{
双x,y;
公共国际比较(b点){
//如果a和b位于同一水平线上,
如果(y==b.y)
//当a在b的左边时,ab.x?+1:0;
//否则,当a低于b时,ab.y?+1:0;
}
}
哪一行?如何存储对象所在的行?如果事先不知道,我们怎么回答?你说的“在同一条线上”是什么意思?它们在一个数组中吗?行是这些对象的成员吗?实现了类似的
?@Dave Costa,这是一个合理的添加,但不是一个要求。我现在再补充一句
class Point implements Comparable<Point> {
double x,y;
public int compareTo(Point b) {
// If a and b lie on the same horizontal line,
if (y == b.y)
// then a < b when a is to the left of b
return x < b.x ? -1 : x > b.x ? +1 : 0;
// Otherwise, a < b when a is below b
return y < b.y ? -1 : y > b.y ? +1 : 0;
}
}