The enhanced for loop for Java Advanced Features (i)

Source: Internet
Author: User
Tags iterable
Preface writes
The for/in loop is the so-called enhanced for loop in JDK5.0, which traverses the array and the set, and uses it to make your code shorter and more refined. Here is a description of the following:


Traditional for loop and enhanced for loop comparison
Customizing your own enhanced for loop
Enhance the limitations of the For loop




One: traditional for loop and enhanced for loop comparison


The traditional array traversal
String[] persons={"John", "Dick", "Harry"};
for (int i=0;i<persons.length;i++) {
System.out.println (Persons[i]);
}
Array traversal using an enhanced for loop
String[] persons={"John", "Dick", "Harry"};
for (String person:persons) {
SYSTEM.OUT.PRINTLN (person);

The traditional iterator traversal set
List<string> persons=new arraylist<string> ();
Persons.add ("John");
Persons.add ("Dick");
Persons.add ("Harry");
For (iterator<string> i=persons.iterator (); I.hasnext ();) {
String Person=i.next ();
SYSTEM.OUT.PRINTLN (person);
}
Traversing a collection with an enhanced for loop
List<string> persons=new arraylist<string> ();
Persons.add ("John");
Persons.add ("Dick");
Persons.add ("Harry");
for (String person:persons) {
SYSTEM.OUT.PRINTLN (person);
}


You can see that using an enhanced for loop makes your code shorter and more refined, and if you feel that this change is not going to work, you can tolerate it, so you can try nesting for loops, and you'll feel the benefits of an enhanced for loop, and there's no code attached.
Two: Customizing your own enhanced for loop
As we all know, an enhanced for loop is output in an intrinsic order of an array or set, if we want to customize the behavior as we traverse it. Here is an example of how to customize your enhanced for loop in reverse order output.
To use an enhanced for loop, you must implement the Iterable interface.


Import Java.util.Iterator;


/**
* A simple reverse output enhanced for loop
* @author
*
*/
public class Reveriterableclass<t> implements iterable<t> {
protected t[] elements;
Public Reveriterableclass (T ... elems) {
This.elements=elems;
This.object= (t[]) new object[ts.length];
}
Public iterator<t> iterator () {
return new iterator<t> () {
private int current=elements.length-1;
public Boolean hasnext () {
Return current>-1;
}


Public T Next () {
return elements[current--];
}


public void Remove () {
throw new Unsupportedoperationexception ("Currently does not support delete operation");
}
};
}
public static void Main (string[] args) {
reveriterableclass<string> iterableclass=new reveriterableclass<string> ("A", "B", "C", "D");
for (String S:iterableclass) {
System.out.println (s);
}
}


}
In this program we customize our output behavior-the reverse output, of course, you can also define your own, just in the next () function to write the code.
Third: Enhance the limitations of the For loop
You cannot access a location in an enhanced for loop, such as the following code:


String[] persons={"John", "Dick", "Harry"};
for (int i=0;i<persons.length;i++) {
System.out.println (i+ ":" +persons[i]);
}


You cannot get this position "I" in the enhanced for loop.
For example, we often use the combination of SQL statements, select fields, when the last field, can not add ",".
String[] fields={"name", "Age", "sex"};
StringBuilder sql=new StringBuilder ("select");
for (int i=0;i<fields.length;i++) {
if (i<fields.length-1) {
Sql.append (fields[i]+ ",");
}else{
Sql.append (Fields[i]);
}
}
Sql.append ("from T_user");
SYSTEM.OUT.PRINTLN (SQL);
This is also not handled in the enhanced for loop.
There is also a deletion of the element, which cannot be done in an enhanced for loop, but it is possible to use his remove () method to delete a qualifying element using the traditional iterator interface traversal.






foreach statement format: for (element type T element variable x: Traverse object obj) {References x's Java statement;} Here are two examples of simple examples of how foreach simplifies programming. The code is as follows: One, the foreach simplifies the array and the collection's traversal import java.util.Arrays;
Import java.util.List;
Import java.util.ArrayList;


public class Testarray {
public static void Main (String args[]) {
Testarray test = new Testarray ();
Test.test1 ();
Test.listtoarray ();
Test.testarray3 ();


}


/**
* The foreach statement outputs a one-dimensional array
*/
public void Test1 () {
Define and initialize an array
int arr[] = {2, 3, 1};
SYSTEM.OUT.PRINTLN ("----1----one-dimensional array before sorting");
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x); Output the value of an array element individually
}


sorting arrays
Arrays.sort (arr);


Use Java new features for Each loop output array
SYSTEM.OUT.PRINTLN ("----1----ordered one-dimensional array");
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x); Output the value of an array element individually
}
}


/**
* The collection is converted to a one-dimensional array
*/
public void Listtoarray () {
Create a list and add elements
list<string> list = new arraylist<string> ();
List.add ("1");
List.add ("3");
List.add ("4");


To output a collection element with a Froeach statement
SYSTEM.OUT.PRINTLN ("----2----froeach statement output set element");
for (String x:list) {
SYSTEM.OUT.PRINTLN (x);
}


Convert ArrayList to an array
Object s[] = List.toarray ();


To output a collection element with a Froeach statement
SYSTEM.OUT.PRINTLN ("----2----an array element converted from a set of Froeach statement output");
for (Object x:s) {
System.out.println (X.tostring ()); Output the value of an array element individually
}
}


/**
* foreach output two dimensional array test
*/
public void TestArray2 () {
int arr2[][] = {4, 3}, {1, 2}};
SYSTEM.OUT.PRINTLN ("----3----foreach output two-dimensional array test");
for (int x[]: arr2) {
for (int e:x) {
System.out.println (e); Output the value of an array element individually
}
}
}


/**
* foreach output three-dimensional array
*/
public void TestArray3 () {
int arr[][][] = {
{{1, 2}, {3, 4}},
{{5, 6}, {7, 8}}
};


SYSTEM.OUT.PRINTLN ("----4----foreach output three-dimensional array test");
For (int[][] a2:arr) {
For (int[] a1:a2) {
for (int x:a1) {
SYSTEM.OUT.PRINTLN (x);
}
}
}
}
Run Result:----1----One-dimensional array before sorting
2
3
1
----1----Sorted one-dimensional array
1
2
3
----2----Froeach Statement output collection elements
1
3
4
----2----An array element converted from the Froeach statement output collection
1
3
4
----4----foreach output three-dimensional array test
1
2
3
4
5
6
7
8


Process finished with exit code 0




Ii. limitations of the foreach statement The above example shows that if you want to refer to an array or an index of a collection, the foreach statement is not possible, and foreach simply passes through the group or collection. Here's an example to see:/**
public class TestArray2 {


public static void Main (String args[]) {
Define a one-dimensional array
int arr[] = new INT[4];
SYSTEM.OUT.PRINTLN ("Output just defined array----" before----unassigned);
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x);
}


Assigning values to an array element by index
SYSTEM.OUT.PRINTLN ("----Assign a value to an array element through a loop variable----");
for (int i = 3; i > 0; i--) {
Arr[i] = i;
}
Array created by looping output
SYSTEM.OUT.PRINTLN ("----assignment, the foreach output creates a good array----");
for (int x:arr) {
SYSTEM.OUT.PRINTLN (x);
}
}
}
Run Result: Outputs the array just defined before----unassigned----
0
0
0
0
----Assign values to an array element through a loop variable----
----assignment, the foreach output creates a good array----
0
1
2
3


Process finished with exit code 0








IV: summary
Enhanced for loops have its benefits, such as simplicity, code elegance, and if you can use an enhanced for loop, be sure to use it first.









Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.