使用Java对点列表进行排序 [英] Sorting a list of points with Java
本文介绍了使用Java对点列表进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个点对象列表,我想按某个坐标排序,比如x值。 Java是否提供了任何有用的机制,还是应该使用常见的排序算法之一?
I have a list of point objects, which I want to sort by a certain coordinate, say the x-values. Does Java provide any useful mechanisms or should I avail myself of one of the common sort algorithms?
推荐答案
是创建自定义 比较器
,并用它来对点列表进行排序
Yes create a custom Comparator
, and use it to sort list of points
class Point{
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point() {
}
}
List<Point> points = new ArrayList<Point>();
points.add(new Point(1, 2));
points.add(new Point(60, 50));
points.add(new Point(50, 3));
Collections.sort(points,new Comparator<Point>() {
public int compare(Point o1, Point o2) {
return Integer.compare(o1.getX(), o2.getX());
}
});
这篇关于使用Java对点列表进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文