A java interview question. Is there any way in java programming other then the loop constructs to iterate through a given collection(an Array) and work on the each element of the collection.
6 Answers
Recursion is one way to do it
void it(Iterator i) {
if (i.hasNext()) {
System.out.println(i.next());
it(i);
}
}
-
4+1: I would point out these even though you can do this, anyone who does this in a real system deserves to be sacked. :P Jun 14, 2011 at 13:49
Other than recursion commons-collection has utility methods that you may use to do stuff on a collection. Note that this api also uses loop constructs internally. But the client code would look like :
CollectionUtils.forAllDo(
yourCollection,
new Closure() {
void execute(java.lang.Object element) {
// do smt with element
}
}
);
Check the CollectionUtils here : http://commons.apache.org/collections/apidocs/org/apache/commons/collections/Closure.html
-
1+1 I like this... the awkward left-handed not-what-anybody-was-expecting approach. I'll just trust it works.– MattJun 14, 2011 at 14:02
Yes, you could recursively go through a function to get the same functionality:
public void iterate(int[] array, int index){
if (index >= array.length){
return;
}else{
//work with element at array[index]
iterate(array, index+1);
}
}
You can interchange an iterative solution for a recursive one. Loops are iterative, so just create a recursive solution instead.
Using recursion we iterate array or collection without using loop. See below recursion method:
public static void iterateArray(int nums[], int index) {
if (nums.length == index) {
return;
}
System.out.print(nums[index] + " ");
iterateArray(nums, index + 1);
}
goto
andconst
keywords which you cannot use anywhere in code.