Are you tired of writing mechanical code every time you write a for loop, especially when you need to traverse arrays or collections, such:
Public voidShowall (collection C ){
For(Iterator iter = C. iterator (); ITER. hasnext ();){
System. Out. println (ITER. Next (). tostring ());
}
}
Public voidShowall (string [] SA ){
For(INT I = 0; I <SA. length; I ++ ){
System. Out. println (SA [I]);
}
}
This code is not only bloated, but also prone to errors (think about it if we accidentally forget to move the iterator or subscript, or accidentally move the subscript in the loop body, it may be worse: A logical judgment is made in the loop body, which further affects the subscript or iterator location. There are many similar examples .) Why can't the compiler help us? In 5.0, we can write as follows:
Public voidShowall (collection C ){
For(Object OBJ: C ){
System. Out. println (obj. tostring ());
}
}
Public voidShowall (string [] SA ){
For(String STR: SA ){
System. Out. println (STR );
}
}
This code is clearer and more concise, isn't it? (Is it a bit like C # foreach ?) With generics, we can even make the first method more beautiful:
Public voidShowall (collection <string> C ){
For(String STR: C ){
System. Out. println (STR );
}
}
With generics and enhanced for loops, we don't have to worry about the annoying for loop expressions and nesting in most cases. The following are exceptions: When you need to access iterator and the lower mark in the loop body, for example, when you need to remove or modify elements in the set or array.
Continued ....
Suppose we want to traverse a set to process the elements. The typical code is:
Void processall (collection C ){
For (iterator I = C. iterator (); I. hasnext (){
Myclass myobject = (myclass) I. Next ();
Myobject. Process ();
}
}
With the for-each loop, we can rewrite the code,
Void processall (collection <myclass> C ){
For (myclass myobject: C)
Myobject. Process ();
}
This code is much clearer than above and avoids forced type conversion.