Java 如何访问双值列表?
我有一个double[]类型的值列表,定义为Java 如何访问双值列表?,java,arrays,list,Java,Arrays,List,我有一个double[]类型的值列表,定义为列表点 列表以[[x0,y0],[x1,y1],[x2,y2]…]的形式给出一组点 如何访问值x0、y0、x1、y1。。。使用for循环 我可以使用for循环访问数组中的值,但如果这些值位于数组列表中,我无法了解如何访问这些值。使用嵌套循环: for(double[] dArr: points) { //iterate through all arrays in the list for(double d: dArr) { //iterate
列表点
列表以[[x0,y0],[x1,y1],[x2,y2]…]的形式给出一组点
如何访问值x0、y0、x1、y1。。。使用for循环
我可以使用for循环访问数组中的值,但如果这些值位于数组列表中,我无法了解如何访问这些值。使用嵌套循环:
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
}
}
使用嵌套循环:
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
}
}
5tingr4y的答案是正确的,但假设所有数组都具有相同的长度(2),则不需要嵌套循环
for (double[] pair : points) {
double x = pair[0];
double y = pair[1];
// Do things with x and y
}
或者,根据示例中的用例,可以使用awt库或JavaFX库中的and类来存储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();
}
List points=new ArrayList();
增加(新的MyPoint(5,10));
用于(MyPoint p:points){
双x=p.getX();
双y=p.getY();
}
5tingr4y的答案是正确的,但假设所有数组都具有相同的长度(2),则不需要嵌套循环
for (double[] pair : points) {
double x = pair[0];
double y = pair[1];
// Do things with x and y
}
或者,根据示例中的用例,可以使用awt库或JavaFX库中的and类来存储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();
}
List points=new ArrayList();
增加(新的MyPoint(5,10));
用于(MyPoint p:points){
双x=p.getX();
双y=p.getY();
}
只需使用foreach遍历列表。“定义为列表点”马上就有问题了。使用List
@Michael这同样糟糕。对于每个项目使用固定数量的值的集合/数组没有意义。所以OP应该使用现有的Point
类中的一个,或者编写自己的类。@Tom这也不坏。应始终避免混合数组和列表。但是,是的,点类是一种方法。只需使用foreach遍历列表。“定义为列表点”马上就有问题了。使用List
@Michael这同样糟糕。对于每个项目使用固定数量的值的集合/数组没有意义。所以OP应该使用现有的Point
类中的一个,或者编写自己的类。@Tom这也不坏。应始终避免混合数组和列表。但是,是的,积分课程是一条路要走。