[JAVA] Please explain what this line of code does in detail in the code below Ar
ID: 3725841 • Letter: #
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
{
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;
}
}
}
Explanation / Answer
Arrays.sort(points, new CompareY());
Basically,Collections class provides static methods for sorting the elements of collection.
We can also sort an array of user defined class.
Method of Collections class for sorting Array of User defined elements.
public void sort(Array(user defined) array, Comparator c): is used to sort the elements of array of user defined class by the given Comparator.
Arrays.sort(points, new CompareY());
So here, points is a user defined class of Point, and CompareY is a class which implements the Comparator interface to sort the points(of user-defined class Point) in either ascending or descending order.
Here in this case, it sort the Y points in descending order.
As a result, we are able to see Y points are sorted in descending order as we see in the output
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.