首页 > 解决方案 > 等价于 java 中的 for x, y in z

问题描述

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

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

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

标签: javapythonloopsfor-loop

解决方案


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

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
}

推荐阅读