Nifty way to iterate over parallel arrays in Java using foreach

后端 未结 8 894
没有蜡笔的小新
没有蜡笔的小新 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:27

    You can use a second constraint in your for loop:

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

    One of my preferred methods for traversing collections is the for-each loop, but as the oracle tutorial mentions, when dealing with parallel collections to use the iterator rather than the for-each.

    The following was an answer by Martin v. Löwis in a similar post:

    it1 = list1.iterator();
    it2 = list2.iterator();
    while(it1.hasNext() && it2.hasNext()) 
    {
       value1 = it1.next();
       value2 = it2.next();
    
       doStuff(value1);
       doStuff(value2);
    }//while
    

    The advantage to the iterator is that it's generic so if you don't know what the collections are being used, use the iterator, otherwise if you know what your collections are then you know the length/size functions and so the regular for-loop with the additional constraint can be used here. (Note I'm being very plural in this post as an interesting possibility would be where the collections used are different e.g. one could be a List and the other an array for instance)

    Hope this helped.

提交回复
热议问题