gpt4 book ai didi

java - float[]的ArrayList,无法检查ArrayList中是否包含float[]

转载 作者:行者123 更新时间:2023-11-29 03:53:00 26 4
gpt4 key购买 nike

我有一个 ArrayList<float[]>我在其中放置了 float 组,用于存储直线的笛卡尔值,即 (x0,y0, x1,y1)。

每次我从 .contains() 执行一个 float 组时,它都会返回 false,即使我可以在调试器中看到它存在。 SO 似乎是在比较内存引用而不是实际值。有什么方法可以让他们比较这些值?

public static void main (String[] args) {
ArrayList <float[]>drawnLines = new ArrayList<float[]>();
float[] line = new float[4];

line[0] = (float)5;
line[1] = (float)12;
line[2] = (float)55;
line[3] = (float)66;

drawnLines.add(line);

float[] linea = new float[4];

linea[0] = (float)5;
linea[1] = (float)12;
linea[2] = (float)55;
linea[3] = (float)66;

if (drawnLines.contains(linea)) {
System.out.println("contians");
}
else {
System.out.println(" does not contian");
}
}

最佳答案

这是因为 line.equals(linea) 为假。

你需要用一个类来包装 float[],这个类定义了你所说的相等。

但是,使用像 Line 这样的类似乎是更好的选择。


public static void main(String[] args) {
List<Line> drawnLines = new ArrayList<Line>();
drawnLines.add(new Line(5, 12, 55, 66));
Line linea = new Line(5, 12, 55, 66);
if (drawnLines.contains(linea))
System.out.println("contains " + linea);
else
System.out.println(" does not contain " + linea);
}

static class Line {
final float x0, y0, x1, y1;

Line(float x0, float y0, float x1, float y1) {
this.x0 = x0;
this.y0 = y0;
this.x1 = x1;
this.y1 = y1;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Line line = (Line) o;
if (Float.compare(line.x0, x0) != 0) return false;
if (Float.compare(line.x1, x1) != 0) return false;
if (Float.compare(line.y0, y0) != 0) return false;
return Float.compare(line.y1, y1) == 0;
}

@Override
public String toString() {
return "Line{" + "x0=" + x0 + ", y0=" + y0 + ", x1=" + x1 + ", y1=" + y1 + '}';
}
}

打印

contains Line{x0=5.0, y0=12.0, x1=55.0, y1=66.0}

关于java - float[]的ArrayList,无法检查ArrayList中是否包含float[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7838865/

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