Nifty way to iterate over parallel arrays in Java using foreach

后端 未结 8 874
没有蜡笔的小新
没有蜡笔的小新 2020-12-13 04:29

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

8条回答
  •  时光说笑
    2020-12-13 05:10

    ArrayIterator lets you avoid indexing, but you can’t use a for-each loop without writing a separate class or at least function. As @Alexei Blue remarks, official recommendation (at The Collection Interface) is: “Use Iterator instead of the for-each construct when you need to: … Iterate over multiple collections in parallel.”:

    import static com.google.common.base.Preconditions.checkArgument;
    import org.apache.commons.collections.iterators.ArrayIterator;
    
    // …
    
      checkArgument(array1.length == array2.length);
      Iterator it1 = ArrayIterator(array1);
      Iterator it2 = ArrayIterator(array2);
      while (it1.hasNext()) {
          doStuff(it1.next());
          doOtherStuff(it2.next());
      }
    

    However:

    • Indexing is natural for arrays – an array is by definition something you index, and a numerical for loop, as in your original code, is perfectly natural and more direct.
    • Key-value pairs naturally form a Map, as @Isaac Truett remarks, so cleanest would be to create maps for all your parallel arrays (so this loop would only be in the factory function that creates the maps), though this would be inefficient if you just want to iterate over them. (Use Multimap if you need to support duplicates.)
    • If you have a lot of these, you could (partially) implement ParallelArrayMap<> (i.e., a map backed by parallel arrays), or maybe ParallelArrayHashMap<> (to add a HashMap if you want efficient lookup by key), and use that, which allows iteration in the original order. This is probably overkill though, but allows a sexy answer.

    That is:

    Map map = new ParallelArrayMap<>(array1, array2);
    for (Map.Entry entry : map.entrySet()) {
      doStuff(entry.getKey());
      doOtherStuff(entry.getValue());
    }
    

    Philosophically, Java style is to have explicit, named types, implemented by classes. So when you say “[I have] parallel arrays [that] store key/value pairs.”, Java replies “Write a ParallelArrayMap class that implements Map (key/value pairs) and that has a constructor that takes parallel arrays, and then you can use entrySet to return a Set that you can iterate over, since Set implements Collection.” – make the structure explicit in a type, implemented by a class.

    For iterating over two parallel collections or arrays, you want to iterate over a Iterable>, which less explicit languages allow you to create with zip (which @Isaac Truett calls wrap). This is not idiomatic Java, however – what are the elements of the pair? See Java: How to write a zip function? What should be the return type? for an extensive discussion of how to write this in Java and why it’s discouraged.

    This is exactly the stylistic tradeoff Java makes: you know exactly what type everything is, and you have to specify and implement it.

提交回复
热议问题