gpt4 book ai didi

java - 为 Arrays.Sort of Points 写一个可比较的

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:26 24 4
gpt4 key购买 nike

我有这段代码:

import java.awt.Point;
import java.util.Arrays;

public class Haupt {

// creates an array of anz Point objects
public static Point[] generatePointArray(int anz) {
Point[] pa = new Point[anz];
for(int i = 0; i < anz; i++) {
int px = (int) (Math.random() * 10);
int py = (int) (Math.random() * 10);
pa[i] = new Point(px,py);
}
return pa;
}

public static void main(String[] args) {
Point[] pointArray = generatePointArray(15);

Arrays.sort(pointArray);


for(int i = 0 ; i < pointArray.length; i++) {
System.out.println("Point: "+pointArray[i] +
" has distance "+pointArray[i].distance(0,0)+
" from origin");
}
}
}

正如您可能看到的,我想对一个点数组进行排序,因此我(几乎)写了一个可比较的:

import java.awt.Point;

public class MyPoint extends Point implements Comparable {
public int compareTo(Object o)
{
Point p = (Point) o;


if () {
return -1;
}
if () {
return 1;
}
return 0;
}

}

我需要在 if() 子句中写什么?

编辑:来自评论

The condition would be that I look after the value of the distance between the point(0,0) and Point (x,y) (If this is even possible

最佳答案

compareTo 方法的实现完全取决于您希望如何对这些点进行排序。一种可行的方法是通过它们的 X 和 Y 坐标:

public class MyPoint extends Point implements Comparable<MyPoint> {
public int compareTo(MyPoint o) {
int retVal = Double.compare(getX(), o.getX());
if (retVal != 0) {
return retVal;
}
return Double.compare(getY(), o.getY());
}
}

或者,您可以使用自定义的 Comparator,而不是创建您自己的实现 Comparable 接口(interface)的类。 .随着 Java 8 的增强,它甚至会非常优雅:

Arrays.sort(
pointArray,
Comparator.comparing(Point::getX).thenComparing(Point::getY)
);

编辑:
评论添加了一个建议,即根据点与原点 (0, 0) 的距离对点进行排序。使用这两种机制也很容易做到这一点。点到原点的距离定义为 sqrt(x*x + y*y)。由于 sqrt 是不影响排序的单调变换,因此可以省略它以获得轻微的性能提升。

作为Comparaable:

public class MyPoint extends Point implements Comparable<MyPoint> {
public int compareTo(MyPoint o) {
return Long.compare(getCompareKey(), o.getCompareKey());
}

private long getCompareKey() {
return (getX() * getX()) + (getY() * getY());
}
}

使用自定义比较器:

Arrays.sort(
pointArray,
Comparator.comparing(p -> (p.getX() * p.getX()) + (p.getY() * p.getY())
);

关于java - 为 Arrays.Sort of Points 写一个可比较的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46283844/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com