One key point of object-oriented programming is abstraction. To achieve it, you should create a class that represents a coloured 3D point, such as:
public class Point {
private final int x;
private final int y;
private final int z;
private int red;
private int green;
private int blue;
public Point(int x, int y, int z) {
this.x = x;
this.y = y;
this.z = z;
}
@Override
public String toString() {
return "(" + x + ", " + y + ", " + z + ")";
}
// TODO getters for x, y and z, plus getters & setters for red, green and blue
}
Note: I've added a very useful toString()
method that will help you debug your code. Getters and setters are left as an exercise :)
Now, if you have an array of points, i.e. Point[] points
, you can use the built-in Arrays.sort
utility method, which accepts an array and a Comparator<Point>
:
Point[] points = new Point[] {
new Point(2, 3, 1),
new Point(2, 1, 4),
new Point(2, 1, 5) };
System.out.println(Arrays.toString(points)); // [(2, 3, 1), (2, 1, 4), (2, 1, 5)]
Comparator<Point> comparator = Comparator.comparingInt(Point::getX)
.thenComparingInt(Point::getY)
.thenComparingInt(Point::getZ);
Arrays.sort(points, comparator);
System.out.println(Arrays.toString(points)); // [(2, 1, 4), (2, 1, 5), (2, 3, 1)]
Note: I'm using Arrays.toString
utility method to create a human-readable string representation of the array.
Pay attention to the definition of the Comparator<Point> comparator
variable: there I'm stating that I want a comparator that will order points based on the int
value returned by the Point.getX()
method, then, if equal, order will be determined by the int
value returned by the Point.getY()
method and, finally, if still equal, order will be determined by the int
value returned by the Point.getZ()
method. This is what the Comparator.comparingInt
and Comparator.thenComparingInt
methods are used for.