我有一个double []类型的值列表,定义为List <double[]> points
该列表以[[x0, y0], [x1, y1], [x2, y2]...]
如何使用for循环访问值x0,y0,x1,y1 ...
我可以使用for循环访问数组中的值,但如果它们位于数组列表中,则无法理解如何执行此操作。
答案 0 :(得分:2)
5tingr4y的答案是正确的,但假设所有数组都有相同的长度(2),那么你不需要嵌套循环。
for (double[] pair : points) {
double x = pair[0];
double y = pair[1];
// Do things with x and y
}
或者在您的示例中给出用例,您可以使用awt库中的Point
和Point2D.Double
类,或者JavaFX库中的Point2D
来存储您的x对和y值。或者你甚至可以自己上课。 e.g。
public class MyPoint {
private double x, y;
public MyPoint(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}
public double getY() {
return y;
}
}
使用MyPoint
的示例,对于前面提到的库类几乎相同。
List<MyPoint> points = new ArrayList<>();
points.add(new MyPoint(5, 10));
for (MyPoint p : points) {
double x = p.getX();
double y = p.getY();
}
答案 1 :(得分:0)
使用嵌套循环:
for(double[] dArr: points) { //iterate through all arrays in the list
for(double d: dArr) { //iterate through all doubles in the current array
//your code
}
}