使用 foreach 在 Java 中迭代并行数组的好方法

2022-01-24 iteration 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.

相关文章