使用 foreach 在 Java 中迭代并行数组的绝妙方法 [英] Nifty way to iterate over parallel arrays in Java using foreach
问题描述
我继承了大量使用并行数组来存储键/值对的代码.这样做实际上是有意义的,但是编写迭代这些值的循环有点尴尬.我真的很喜欢新的 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
包装器将隐藏边界检查.
The Iterable<Pair<K,V>>
wrapper would hide the bounds checking.
这篇关于使用 foreach 在 Java 中迭代并行数组的绝妙方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!