Modify the LabeledPoint class of of Exercise P16.12 so that it implements the Co
ID: 3640741 • Letter: M
Question
Modify the LabeledPoint class of of Exercise P16.12 so that it implements the Comparable interface. Sort points first by their x-coordinates. If two points have the same x-coordinate, sort them by their y-coordinates. If two points have the same x- and y-coordinates, sort them by their label. Write a tester program that checks all cases.16.12
A labeled point has x- and y-coordinates and a string label. Provide a class LabeledPoint with a constructor LabeledPoint(int x, int y, String label) and hashCode and equals methods. Two labeled points are considered the same when they have the same location and label.
Explanation / Answer
public class LabeledPoint implements Comparable<LabeledPoint>
{
private double x,y;
private String label;
...
public int compareTo(LabeledPoint rhs)
{
if(rhs.x != x)
{
if(x < rhs.x)
return -1;
else
return 1;
}
else if(rhs.y != y)
{
if(y < rhs.y)
return -1;
else
return 1;
}
else
{
return label.compareTo(rhs.label);
}
}
}
I leave the test class up to you - making test cases is trivial.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.