comparable interface

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?
LVL 3
jayrodAsked:
Who is Participating?
 
lcwidingCommented:
The distance formula coudl be used as follows:

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.
0
 
zzynxSoftware engineerCommented:
You could use the "distance" from the point (0,0)
0
 
zzynxSoftware engineerCommented:
It's all a matter of taste: you could use
- x+y
- x*y
- x^2 + y^2
- ...
0
Cloud Class® Course: Ruby Fundamentals

This course will introduce you to Ruby, as well as teach you about classes, methods, variables, data structures, loops, enumerable methods, and finishing touches.

 
zzynxSoftware engineerCommented:
What exactly do you want to achieve?
0
 
petmagdyCommented:
like this

public int compare( Point comapred )
{
 // I am begger than compared
return 1;

//tie
return 0;
 
 // I am less than compared
return -1;
}
0
 
petmagdyCommented:
offcourse u understand the silly mispelling mistakes in the code i wrote
0
 
jayrodAuthor Commented:
I guess consistincey..

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
0
 
jayrodAuthor Commented:
hmm.. the distance from 0,0 would be interesting.. don't remember the distance formula though :P
0
 
zzynxSoftware engineerCommented:
>> don't remember the distance formula though
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




0
 
zzynxSoftware engineerCommented:
jayrod, why didn't you split the points? I was the one talking about the "distance"...
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.