使用foreach在Java中迭代并行数组的巧妙方式 [英] Nifty way to iterate over parallel arrays in Java using foreach

查看:195
本文介绍了使用foreach在Java中迭代并行数组的巧妙方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承了大量的代码,广泛使用并行数组来存储键/值对。这样做实际上是有道理的,但是编写遍历这些值的循环是有点尴尬的。我真的很喜欢新的Java的foreach结构,但似乎没有一种方法可以用这个方法遍历并行列表。
$ b $ p

使用正常的 for 循环,我可以很容易地做到这一点:

  for(int i = 0; i< ; list1.length; ++ i){
doStuff(list1 [i]);
doStuff(list2 [i]);





$ b但是在我看来,这不是纯粹的语义,因为我们没有检查在迭代期间 list2 的范围。有没有一些聪明的语法类似的for-每个我可以使用平行列表?

解决方案

我会使用一个 Map 我自己。但是,在你的说法中,一对数组在你的情况下是有意义的,那么一个实用方法如何处理你的两个数组并返回一个 Iterable 包装器?



概念上:

pre $ for(Pair< K,V> p:wrap(list1 ,list2)){
doStuff(p.getKey());
doStuff(p.getValue());





Iterable > ; wrapper会隐藏边界检查。


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.

With a normal for loop, I can do this easily:

for (int i = 0; i < list1.length; ++i) {
    doStuff(list1[i]);
    doStuff(list2[i]);
}

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?

解决方案

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?

Conceptually:

for (Pair<K,V> p : wrap(list1, list2)) {
    doStuff(p.getKey());
    doStuff(p.getValue());
}

The Iterable<Pair<K,V>> wrapper would hide the bounds checking.

这篇关于使用foreach在Java中迭代并行数组的巧妙方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆