Question: [JAVA] Please explain what this line of code does in detail in the code below Arrays.sort(points, new CompareY()); ------------------------------------------------------------------------------------------- import java.util.Arrays; public class SortPoints {
[JAVA]
Please explain what this line of code does in detail in the code below
Arrays.sort(points, new CompareY());
-------------------------------------------------------------------------------------------
import java.util.Arrays;
public class SortPoints
{
public static void main(String[] args)
{
Point[] points = new Point[100];
for (int i = 0; i < points.length; i++)
{
points [i] = new Point(Math.random() * 100, Math.random() * 100);
}
System.out.println("Sort X points");
Arrays.sort(points);
for (int i = 0; i < points.length; i++)
{
System.out.println(points [i]);
}
System.out.println("Sort Y points");
Arrays.sort(points, new CompareY());
for (int i = 0; i < points.length; i++)
{
System.out.println(points [i]);
}
}
public static class Point implements Comparable
{
double x;
double y;
Point(double x, double y)
{
this.x = x;
this.y = y;
}
public int compareTo(Point c2)
{
if(this.x < c2.x)
return - 1;
else if (this.x == c2.x)
{
if(this.y < c2.y)
return - 1;
else if (this.y == c2.y)
return 0;
else return 1;
}
else return 1;
}
public String toString()
{
return "[" + x + ", " + y + "]";
}
}
public static class CompareY implements java.util.Comparator
{
public int compare(Point c1, Point c2)
{
if (c1.y < c2.y)
return -1;
else if (c1.y == c2.y)
{
if(c1.x < c2.x)
return - 1;
else if (c1.x == c2.x)
return 0;
else return 1;
}
else return 1;
}
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
