[Webinar] Streamline your web hosting managementRegister Today

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 231
  • Last Modified:

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?
0
jayrod
Asked:
jayrod
  • 5
  • 2
  • 2
  • +1
1 Solution
 
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
 
zzynxSoftware engineerCommented:
What exactly do you want to achieve?
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
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
 
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:
jayrod, why didn't you split the points? I was the one talking about the "distance"...
0

Featured Post

The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

  • 5
  • 2
  • 2
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now