Solved

Posted on 2004-10-29

I'm implementing a simple point class

class point implements Comparable{

int x

int y

}

in the compareTo method.. how would I specify less than and Greater than?

class point implements Comparable{

int x

int y

}

in the compareTo method.. how would I specify less than and Greater than?

10 Comments

public int compare( Point comapred )

{

// I am begger than compared

return 1;

//tie

return 0;

// I am less than compared

return -1;

}

because point 2,2 is equal to 2,2

but 3,2 is != 2,3 but in this case.. which is bigger? because 3+2 = 5 and 2+3 = 5 so that doesn't work

square root from ( x^2 + y^2 )

You'll always have points that will be "equal" (all points that lie on a circle with (0,0) as center will give equality)

>>because 3+2 = 5 and 2+3 = 5 so that doesn't work

Unless you add && pt1.x==pt2.x && pt1.y==pt2.y

public int compare(Point compared)

{

long dist = x * x + y * y;

long dist2 = compared.x * compared.x + compared.y * compared.y;

if (dist == dist2)

return 0;

if (dist < dist2)

return -1;

else

return 1;

}

The issue here is that, a you pointed out, 3,2 is not 2,3 but would come out equal in this situation. This does get to be tricky, as comparison in a situation like this is probably not going to equate to being the same.

By clicking you are agreeing to Experts Exchange's Terms of Use.

Title | # Comments | Views | Activity |
---|---|---|---|

squareUp challenge | 22 | 67 | |

countClumps challenge | 10 | 52 | |

Jave - Remove carriage return + special characters from text | 3 | 33 | |

endX challenge | 2 | 19 |

Join the community of 500,000 technology professionals and ask your questions.

Connect with top rated Experts

**18** Experts available now in Live!