繁体   English   中英

相当于java中的x, y in z

[英]Equivalent of for x, y in z in java

在 python 中,你可以使用结构for x in [a, b, c, d] for 循环。 这可以使用 java 中的 foreach 循环来复制。

如果我想在 java 中复制一个for x, y in z循环,例如下面的循环呢?

for x_off, y_off in ( (1, 2), (-1, 2), (1, -2), (-1, -2), (2, 1), (-2, 1), (2, -1), (-2, -1) ):
    #do something

我最终只为每个索引使用变量。 但这对于每个内部数组都有大量计数的二维数组没有用。

int[][] offsets = new int[][] { {0, 1}, {0, -1}, {1, 0}, {-1, 0}, {1, 1}, {1, -1}, {-1, 1}, {-1, -1} };

for(int[] offset: offsets) {
    int x = offset[0], y = offset[1];
    // do something with x and y

您应该创建一个用于存储三个值的类:

final class Point3D {
    private final int x, y, z;
    // constructor, getters, and equals/hashCode/toString here
}

然后您可以使用带有增强的 for 循环的数组初始值设定项:

for (Point3D point : new Point3D[] { new Point3D(1, 1, 1), new Point3D(-1, 1, 1),
                                     new Point3D(-1, -1, 1), new Point3D(1, -1, 1) }) {
    // code here
}

如果单独创建数组,它会读起来更好,特别是如果有很多点:

Point3D[] points = {
        new Point3D( 1,  1,  1), new Point3D(-1,  1,  1),
        new Point3D(-1, -1,  1), new Point3D( 1, -1,  1),
        new Point3D( 1,  1, -1), new Point3D(-1,  1, -1),
        new Point3D(-1, -1, -1), new Point3D( 1, -1, -1)
};
for (Point3D point : points) {
    // code here
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM