java - 等价于 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
解决方案
您应该创建一个用于存储三个值的类:
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
}
推荐阅读
- vba - 在 VBA 中将单词范围转换为带有 HTML 标记的字符串
- java - ([D@7852e922) 尝试打印双精度数组时输出错误
- php - 如何在 PHP 中设置可以通过方法更改的可变类属性?
- python - 将句子中的单词更改为特殊字符
- debugging - gdbserver:目标描述指定未知架构“aarch64”
- git - 删除提交历史而不恢复
- python-3.x - 使用return语句时循环回到菜单?
- python - Keras 训练时间异常
- python - 在 python twisted 中映射请求响应
- jquery - 在 MVC 5 中,如何根据另一个下拉值删除所需的属性?