java距离排序
时间: 2023-07-01 19:24:41 浏览: 43
Java中可以通过实现Comparator接口来实现距离排序。假设有一个名为Point的类表示二维平面上的点,其中包含x和y坐标属性,可以按照以下方式实现距离排序:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class Point {
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance() {
return Math.sqrt(x * x + y * y);
}
public static void main(String[] args) {
List<Point> points = new ArrayList<>();
points.add(new Point(1, 2));
points.add(new Point(3, 4));
points.add(new Point(5, 6));
// 按照距离排序
Collections.sort(points, new Comparator<Point>() {
@Override
public int compare(Point p1, Point p2) {
return Double.compare(p1.distance(), p2.distance());
}
});
for (Point point : points) {
System.out.println(point.distance());
}
}
}
```
上述代码中,通过实现Comparator接口中的compare方法,将点按照距离从小到大排序。具体实现中,使用了Collections.sort方法对点进行排序,其中传入了一个匿名内部类,实现了Comparator接口中的compare方法。在compare方法中,通过调用distance方法计算出两个点之间的距离,并返回比较结果。最终打印出了按照距离排序后的点。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)