Nifty way to iterate over parallel arrays in Java using foreach(使用 foreach 在 Java 中迭代并行数组的好方法)
问题描述
我继承了一堆代码,这些代码大量使用并行数组来存储键/值对.这样做实际上是有意义的,但是编写遍历这些值的循环有点尴尬.我真的很喜欢新的 Java foreach 构造,但似乎没有办法使用它来迭代并行列表.
I've inherited a bunch of code that makes extensive use of parallel arrays to store key/value pairs. It actually made sense to do it this way, but it's sort of awkward to write loops that iterate over these values. I really like the new Java foreach construct, but it does not seem like there is a way to iterate over parallel lists using this.
使用普通的 for 循环,我可以轻松做到这一点:
With a normal for loop, I can do this easily:
for (int i = 0; i < list1.length; ++i) {
doStuff(list1[i]);
doStuff(list2[i]);
}
但在我看来,这在语义上并不纯粹,因为我们没有在迭代期间检查 list2 的边界.是否有一些类似于 for-each 的巧妙语法可以用于并行列表?
But in my opinion this is not semantically pure, since we are not checking the bounds of list2 during iteration. Is there some clever syntax similar to the for-each that I can use with parallel lists?
推荐答案
我自己会使用 Map.但是相信你的话,一对数组在你的情况下是有意义的,那么一个实用方法会接受你的两个数组并返回一个 Iterable 包装器吗?
I would use a Map myself. But taking you at your word that a pair of arrays makes sense in your case, how about a utility method that takes your two arrays and returns an Iterable wrapper?
概念上:
for (Pair<K,V> p : wrap(list1, list2)) {
doStuff(p.getKey());
doStuff(p.getValue());
}
Iterable<Pair<K,V>> 包装器会隐藏边界检查.
The Iterable<Pair<K,V>> wrapper would hide the bounds checking.
这篇关于使用 foreach 在 Java 中迭代并行数组的好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 foreach 在 Java 中迭代并行数组的好方法
基础教程推荐
- 使用堆栈算法进行括号/括号匹配 2022-01-01
- 问题http://apache.org/xml/features/xinclude测试日志4j 2 2022-01-01
- 无法复制:“比较方法违反了它的一般约定!" 2022-01-01
- REST Web 服务返回 415 - 不支持的媒体类型 2022-01-01
- Struts2 URL 无法访问 2022-01-01
- Spring AOP错误无法懒惰地为此建议构建thisJoinPoin 2022-09-13
- 修改 void 函数的输入参数,然后读取 2022-01-01
- 如何对 Java Hashmap 中的值求和 2022-01-01
- RabbitMQ:消息保持“未确认"; 2022-01-01
- 存储 20 位数字的数据类型 2022-01-01
