
Java 如何对自定义类Vector进行排序
假如自定义类是点类,如果想用两种或者以上的规则进行排序,例如一种是按照X坐标进行排序,一种是按照Y坐标进行排序,该怎么写?...
假如自定义类是点类,如果想用两种或者以上的规则进行排序,例如一种是按照X坐标进行排序,一种是按照Y坐标进行排序,该怎么写?
展开
2个回答
展开全部
你好,用comparable接口我帮你写了个例子:
package vectorsort;
public class Point implements Comparable<Point>{
private float x;
private float y;
public Point(float x, float y) {
super();
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
@Override
public int compareTo(Point comparePoint) {
int xcomp = (int)((Point)comparePoint).getX();
// 比较x坐标
return (int)(this.getX()-xcomp);
}
public static void main(String[] args) {
Point p1 = new Point(1.0f,2.0f);
Point p2 = new Point(1.5f,2.6f);
System.out.println("x坐标比较结果:"+p1.compareTo(p2));
}
}
O(∩_∩)O~温馨提示O(∩_∩)O~
真心希望你能采纳我的回答,如有不明白,可以继续追问,若满意,记得及时采纳。
package vectorsort;
public class Point implements Comparable<Point>{
private float x;
private float y;
public Point(float x, float y) {
super();
this.x = x;
this.y = y;
}
public float getX() {
return x;
}
public void setX(float x) {
this.x = x;
}
public float getY() {
return y;
}
public void setY(float y) {
this.y = y;
}
@Override
public int compareTo(Point comparePoint) {
int xcomp = (int)((Point)comparePoint).getX();
// 比较x坐标
return (int)(this.getX()-xcomp);
}
public static void main(String[] args) {
Point p1 = new Point(1.0f,2.0f);
Point p2 = new Point(1.5f,2.6f);
System.out.println("x坐标比较结果:"+p1.compareTo(p2));
}
}
O(∩_∩)O~温馨提示O(∩_∩)O~
真心希望你能采纳我的回答,如有不明白,可以继续追问,若满意,记得及时采纳。
追问
我问的是排序,不是比较两个点~
展开全部
Collections.sort(vector, new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if (o1 != null && o2 != null) {
return o1.getOrder().compareTo(o2.getOrder());
}
return 0;
}
});
@Override
public int compare(Object o1, Object o2) {
// TODO Auto-generated method stub
if (o1 != null && o2 != null) {
return o1.getOrder().compareTo(o2.getOrder());
}
return 0;
}
});
追问
我想一种情况对X坐标进行排序,另一种情况对Y坐标进行排序,好像上面的代码没有体现对多种规则进行排序。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询