J2se 1.5 new features: enhanced for Loop
J2se 1.5 provides another form of for loop. With this form of for loop, you can traverse objects of the array, collection, and Other types in a simpler way. This article describes how to use this type of loop, describes how to define classes that can be traversed in this way, and explains some common problems related to this mechanism.
In Java programs, when "processing" one by one -- or "traversing" -- elements in an array or collection, A for loop is generally used (of course, it is not impossible to use other types of loops. I just don't know if the word "for" is short or because the meaning of the word "for" is better than this operation, in this case, the for loop is much more commonly used than other loops ).
For traversing arrays, this loop is generally written as follows:
Listing 1: traditional methods of traversing Arrays
/* Create an array */
Int [] integers = {1, 2, 3, 4 };
/* Start traversal */
For (Int J = 0; j <integers. length; j ++ ){
Int I = integers [J];
System. Out. println (I );
}
For traversing collection objects, this loop usually adopts the following form:
Listing 2: traditional methods for Traversing collection objects
/* Create a collection */
String [] strings = {"A", "B", "C", "D "};
Collection stringlist = java. util. arrays. aslist (strings );
/* Start traversal */
For (iterator itr = stringlist. iterator (); itr. hasnext ();){
Object STR = itr. Next ();
System. Out. println (STR );
}
Another form of for loop is introduced in j2se 1.5, the latest version of Java. With the help of this form of for loop, we can now use a simpler way to traverse the work.
--------------------------------------------------------------------------------
1. The second for Loop
Not strictly speaking, the second for loop in Java is basically in this format:
For (loop variable type loop variable name: object to be traversed) loop body
With this syntax, you can use the following method to traverse an array:
Listing 3: A simple way to traverse Arrays
/* Create an array */
Int [] integers = {1, 2, 3, 4 };
/* Start traversal */
For (int I: integers ){
System. Out. println (I);/* output "1", "2", "3", and "4" in sequence "*/
}
The for loop used here will be seen as this form during compilation:
Listing 4: simple equivalent code for Traversing Arrays
/* Create an array */
Int [] integers = {1, 2, 3, 4 };
/* Start traversal */
For (INT variable name a = 0; variable name a <integers. length; variable name a ++ ){
System. Out. println (integers [variable name a]);/* output "1", "2", "3", "4 "*/
}
The variable name a here is a name automatically generated by the compiler that will not cause confusion.
The following method can be used to traverse a collection:
Listing 5: a simple way to traverse a collection
/* Create a collection */
String [] strings = {"A", "B", "C", "D "};
Collection list = java. util. arrays. aslist (strings );
/* Start traversal */
For (Object STR: List ){
System. Out. println (STR);/* output "A", "B", "C", and "D" in sequence "*/
}
The for loop used here will be seen as this form during compilation:
Listing 6: simple equivalent code for Traversing collection
/* Create a collection */
String [] strings = {"A", "B", "C", "D "};
Collection stringlist = java. util. arrays. aslist (strings );
/* Start traversal */
For (iterator variable name B = List. iterator (); variable name B. hasnext ();){
System. Out. println (variable name: B. Next ();/* output "A", "B", "C", "D "*/
}
Here, "variable name B" is also a name automatically generated by the compiler that will not cause confusion.
During compilation, the j2se 1.5 compiler regards this form of for loop as a corresponding traditional form, so there is no need to worry about performance issues.
Why "foreach" and "in" are not used
Java uses "for" (instead of "foreach" with a clearer meaning) to guide a loop called "For-each loop" and uses ": "(rather than" in "with more explicit meaning) to split the name of the loop variable and the object to be traversed. The main reason for this is to avoid compatibility issues due to the introduction of new keywords. in Java, keywords cannot be used as variable names, although the name "foreach" is not very many, "in" is a name often used to represent the input stream (such as Java. lang. in the system class, there is a static attribute named "in", indicating "standard input stream ").
You can use clever design syntax to allow keywords to be used as common identifiers only if they have special meanings in a specific context. However, this method makes the syntax more complex and is not widely used.
--------------------------------------------------------------------------------
2. Prevent modifying loop variables in the loop body
By default, the compiler allows you to assign a value to the variable in the loop body of the second for loop. However, this method is not recommended because it has no impact on the situations of external circulation and may cause difficulties in understanding the code.
Java provides a mechanism to block such operations during compilation. The specific method is to add a "final" modifier before the loop variable type. In this way, assigning values to the loop variables in the loop body will lead to a compilation error. With this mechanism, you can effectively prevent the "Modify loop variable in the loop body" Operation intentionally or unintentionally.
Listing 7: re-assignment prohibited
Int [] integers = {1, 2, 3, 4 };
For (final int I: integers ){
I = I/2;/* Compilation Error */
}
Note: This only disables the re-assignment of cyclic variables. Assigning values to the attributes of a loop variable or calling a method that changes the content of the loop variable is not forbidden.
Listing 8: modifying the status is allowed.
Random [] randoms = new random [] {newrandom (1), new random (2), new random (3 )};
For (final random R: randoms ){
R. setseed (4);/* set all random objects to use the same seed */
System. Out. println (R. nextlong ();/* the same seed and the first result */
}
3. Type compatibility problems
To ensure that the cyclic variables are safely assigned values at the beginning of each loop, j2se 1.5 imposes certain limitations on the type of the cyclic variables. Under these restrictions, the type of the cyclic variable can be as follows:
The type of the cyclic variable can be the same as that of the element in the object to be traversed. For example, an int type cyclic variable is used to traverse an int [] type array, and an object type cyclic variable is used to traverse a collection.
Listing 9: use cyclic variables of the same type as the elements in the object to be traversed
Int [] integers = {1, 2, 3, 4 };
For (int I: integers ){
System. Out. println (I);/* output "1", "2", "3", and "4" in sequence "*/
}
The type of the cyclic variable can be the parent type of the element in the object to be traversed. For example, an int-type cyclic variable is used to traverse a byte [] array, and an object-type cyclic variable is used to traverse a collection <string> (all elements are string collections).
Listing 10: Use the loop variable of the upper-level type of the element in the object to be traversed
String [] strings = {"A", "B", "C", "D "};
Collection <string> List = java. util. arrays. aslist (strings );
For (Object STR: List ){
System. Out. println (STR);/* output "A", "B", "C", and "D" in sequence "*/
}
The type of the cyclic variable can be automatically converted to the type of the element in the object to be traversed. J2se 1.5 contains the "autoboxing/auto-unboxing" mechanism, allowing the compiler to automatically convert between the basic type and Their Wrapper class when necessary. Therefore, it is feasible to use integer-type cyclic variables to traverse an int [] array or byte-type cyclic variables to traverse a collection <byte>.
Listing 11: cyclic variables that can be automatically converted to the type of elements in the object to be traversed
Int [] integers = {1, 2, 3, 4 };
For (integer I: integers ){
System. Out. println (I);/* output "1", "2", "3", and "4" in sequence "*/
}
Note that the "element type" here is determined by the object to be traversed-if it is an object []-type array, the element type is object, this is true even if all the objects in it are string objects.
Collection of element types can be limited
As of j2se 1.4, the types of objects stored in the collection cannot be limited in Java programs-they are all considered the most common object objects. This problem was solved only after the general mechanism was introduced in j2se 1.5. Currently, collection <t> can be used to indicate that all element types are t collections, such as collection <string> and collection <integer>. However, t here cannot be a simple type, and the writing method like collection <int> is not accepted.
--------------------------------------------------------------------------------
4. prerequisites for such Traversal
There are two types of objects that can be traversed through this method-arrays and instances of classes that implement the java. Lang. iterable interface. Trying to put the result in another type of expression at this position will only cause a prompt message "foreach not applicable to expression type" during compilation.
The Java. Lang. iterable interface defines only one method:
Iterator ()
Returns an object that implements the java. util. iterator interface.
The Java. util. iterator interface defines the following three methods:
Hasnext ()
Returns whether there are any unaccessed objects.
Next ()
Returns the next unaccessed object.
Remove ()
Removes the last object returned by next () from the retrieved object. This is an optional operation. If you do not want to provide this function, you can throw an unsupportedoperationexception during implementation. Because this method has no chance to be called throughout the cycle, whether to provide this function is not affected here.
With these two interfaces, You can implement classes that can be traversed in this way.
Listing 12: A class that can retrieve 10 object Elements
Import java. util .*;
Class tenobjects implements iterable {
Public iteratoriterator (){
Return new iterator (){
Private int COUNT = 0;
Public booleanhasnext (){
Return (count <10 );
}
Public object next (){
Return newinteger (count ++ );
}
Public void remove (){
Throw newunsupportedoperationexception ();
}
};
}
Public static voidmain (string [] ARGs)
{
Tenobjects objects = new tenobjects ();
For (object I: Objects)
{
System. Out. println (I);/* output ten integers from "0" to "9" in sequence */
}
}
}
Collection qualifications
In the j2se 1.5 API, all types of objects that can be traversed in this way are the child types of Java. util. collection. It looks like Java. util. Collection has obtained special treatment from the compiler.
However, in j2se1.5, java. util. Collection is defined as a sub-interface of Java. Lang. iterable. The compiler does not take special care of collection.
Theoretically, some container classes that refuse to implement collection interfaces can be created, and they can be traversed in the same way as collections. However, such containers may not be widely circulated due to compatibility issues.
Naming of several methods
In Java. lang. in the iterable interface, iterator () is used instead of getiterator (); while Java. util. hasnext () and next () are also used in the iterator interface, instead of hasnextelement () and getnextelement (). The reason for this is that the designers of javacollections framework think that these methods are often called frequently (every time a row is squeezed), so it is more appropriate to use a shorter name.
--------------------------------------------------------------------------------
5. Add more precise type control
If you want to use a type that is more accurate than the object type when traversing custom objects, You need to implement Java. lang. iterable interface and Java. util. when using the iterator interface, you can use the generic mechanism in j2se 1.5 to assign some types.
If you want to set the type of the cyclic variable to T, the assignment is as follows:
All the places where java. Lang. iterable is to appear are written as "iterable <t> ".
All the places where java. util. iterator appears are written as "iterator <t> ".
When implementing the java. util. iterator interface, t is used as the return value type of the next () method.
Note that t cannot be a basic type. If you want to use the basic type as the cyclic variable, use their wrap class to replace T here, and then use the auto-unboxing mechanism to achieve the approximate goal.
Listing 13: Use int type cyclic variables to traverse a class that can retrieve 10 integer Elements
Import java. util .*;
Public class tenintegers implementsiterable <integer> {
Publiciterator <integer> iterator (){
Return newiterator <integer> (){
Private int COUNT = 0;
Public booleanhasnext (){
Return (count <10 );
}
Public integer next (){
Returninteger. valueof (count ++ );
}
Public void remove (){
Throw newunsupportedoperationexception ();
}
};
}
Public static voidmain (string [] ARGs)
{
Tenintegers integers = new tenintegers ();
For (int I: integers)
{
System. Out. println (I);/* output ten integers from "0" to "9" in sequence */
}
}
}
In addition, a class can only implement the java. Lang. iterable interface once, even if different types are used in the brackets. Similar to "Class A implements iterable <string>, iterable <integer>", it cannot be compiled. Therefore, there is no way to make an object that can be traversed in such a time period. Integer and string can be used as the type of the cyclic variable (of course, changing them to the other two classes without inheritance and automatic conversion will not work ).
6. Summary
With the second for loop introduced in j2se 1.5, you can perform traversal in a simpler way. Objects that can be traversed in this way can be arrays, collections, or any other class that implements the java. Lang. iterable interface. By using the generic mechanism introduced in j2se 1.5, You can precisely control the type of loop variables that can be used. In addition, the code written in this way will be automatically treated as the same form as the traditional method during compilation, so you don't have to worry about extra performance costs.
This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/remote_roamer/archive/2009/10/28/4737953.aspx