JDK-6402294 : Enhance the new for loop to loop over 1 or more collections
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 6
  • Priority: P4
  • Status: Closed
  • Resolution: Not an Issue
  • OS: linux
  • CPU: x86
  • Submitted: 2006-03-22
  • Updated: 2010-04-04
  • Resolved: 2006-11-03
Related Reports
Relates :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
When using the new for loop for iterating over collections, there is no way to specify more than one collection to iterate over.

JUSTIFICATION :
When dealing with collections of different datatypes that have to be joined over a loop iterators are used instead of get() methods, for an actual or expected performance advantages. This leads to a lot of boilerplate code of declaring iterators over various collections and calling next() over them, when ideally the
new for loop should simplify the process.

EXPECTED VERSUS ACTUAL BEHAVIOR :
EXPECTED -

for(Object o : list1, int i : list2, String s : list3){
do something
}
ACTUAL -
ListIterator <Integer> it1 = list2.getListIterator();
ListIterator <String> it2 = list3.getListIterator();
int i;
String s;
for(Object o : list1){
i = it1.next();
s = it2.next();
do something
}

Comments
EVALUATION Your use case: for(Object o : list1, int i : list2, String s : list3) { do something with o,i,s } requires that list1, list2 and list3 have the same number of elements. If hasNext() is true for o and s, but false for i, then should we swallow the NoSuchElementException thrown by i.next(), set i=null and execute the loop body anyway? There's no way for you to catch the exception in the loop body; you'd have to test for i==null. But what if the collections themselves contain null values? If we do throw a NoSuchElementException, then you can wrap the whole for construct in try{...}catch(NoSuchElementException){...} ... but what if two collections are exhausted simultaneously? Do you want only one exception thrown that describes the first collection to be exhausted, or one exception per exhausted collection, or one exception that describes the state of all collections (exhausted or not)? Does the order of these exceptions matter? (i is given before s, but maybe the compiler does some parallelisation and s.next() gets called before i.next(), so NoSuchElementException for s is thrown first.) As you can see, the enhanced for loop could get very complicated, very fast. This is why it's so very simple. If you need multiple iterators which are logically related, then your current code is actually quite nice (it shows that list1 is 'in charge' of the iteration). Otherwise, the basic for loop is still available to handle complex questions about when hasNext() is false for particular collections, etc.
03-11-2006