Reputation: 149
I have array with points: Point[] p = new Point[]
I want to sort it by x, and then by y. Meaning, If I have
Point A = (1, 2)
Point B = (2, 1)
Point C = (1, 3)
Point D = (2, 2)
After sorting, I will get: [(1,2), (1,3), (2,1), (2,2)]
I try to use Arrays.sort()
, but point isn't comparable. There is an easy way to do that?
Upvotes: 1
Views: 5559
Reputation: 12523
You can use Arrays.sort
with a custom Comparer<Point>
:
Arrays.sort(p, new Comparator<Point>() {
int compare(Point a, Point b) {
int xComp = Integer.compare(a.x, b.x);
if(xComp == 0)
return Integer.compare(a.y, b.y);
else
return xComp;
}
});
Sidenotes:
Point
objects may be null
, you must handle this
in compareTo
.Point
is not an AWT point but your own
class, you'd better let it implement Comparable
.Upvotes: 3
Reputation: 2848
Since Point does not implement comparable you can create your own class for comparison:
public class Sorter implements Comparator
{
public int compare(Object o1, Object o2)
{
Point pointOne = (Point)o1;
Point pointTwo = (Point)o2;
return ((pointOne.getX()+pointOne.getY())+"").compareTo(((pointTwo.getX()+pointTwo.getY())+""));
}
}
Then yo can use this Sorter class:
void mySortingFunc(Point[] points)
{
Arrays.sort(points, new Sorter());
}
Upvotes: 0
Reputation: 2340
Let Point
implement the Comparable
interface, and override its compareTo
method to suit your needs.
@Override
public int compareTo(Point p) {
if (this.x != p.x) {
return Integer.compareTo(this.x, p.x);
} else {
return Integer.compareTo(this.y, p.y);
}
}
Read more: http://javarevisited.blogspot.com/2012/01/how-to-sort-arraylist-in-java-example.html#ixzz2S2i9k5V3
This requires editing the Point
class. If that's not possible, see other answers for alternative solutions.
Upvotes: 1
Reputation: 122008
you can try (pseudo code).
Arrays.sort(p, new Comparator<Point >() {
public int compare(Point p1, Point p2) {
//here operations and return
}
});
Upvotes: 1