How to go through the collection without using any loop construct?
A java interview question. Is there any way in java programming other then the loop co开发者_如何转开发nstructs to iterate through a given collection(an Array) and work on the each element of the collection.
Recursion is one way to do it
void it(Iterator i) {
if (i.hasNext()) {
System.out.println(i.next());
it(i);
}
}
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
Recursion ?
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);
}
精彩评论