A variable in a cyclic condition in a for loop is only a one-time value! Look at the final picture in detail
The foreach statement is Java5 new, and foreach has good performance when traversing arrays and collections.
foreach is a simplification of the for statement, but foreach does not replace the for loop. It can be said that any foreach can be rewritten as a for loop, but vice versa.
foreach is not a keyword in java. A Foreach Loop object is generally a collection, List, ArrayList, LinkedList, Vector, array, and so on.
foreach Format:
for (element type T Each loop element's name O: Loop object) {
Operate on O
}
One, the common use way.
1. Foreach traversal array.
/**
* Description:
* Created by Ascend on 2016/7/8.
* * Public
class Client {public
static void Main (string[] args) {
string[] names = {"Beibei", "Jingjing"};
for (String name:names) {
System.out.println (name);}}}
2.foreach Traverse list.
/**
* Description:
* Created by Ascend on 2016/7/8.
* * Public
class Client {public
static void Main (string[] args) {
list<string> List = new ArrayList ();
list.add ("a");
List.add ("B");
List.add ("C");
for (String str:list) {
System.out.println (str);}}}
Second, limitations.
foreach can traverse an array or a collection, but it can only be traversed, unable to modify the array or collection during traversal, and the for loop can modify the source arrays or collections during traversal.
1. Array
/**
* Description:
* Created by Ascend on 2016/7/8.
* * Public
class Client {public
static void Main (string[] args) {
string[] names = {"Beibei", "Jingjing"};
for (String name:names) {
name = ' Huanhuan ';
}
foreach
System.out.println ("foreach:" +arrays.tostring (names));
For for
(int i = 0; i < names.length i++) {
names[i] = "Huanhuan";
}
System.out.println ("For:" +arrays.tostring (names));
}
Output:
Foreach:[beibei, Jingjing]
For:[huanhuan, Huanhuan]
2. Collection
/**
* Description:
* Created by Ascend on 2016/7/8.
* * Public
class Client {public
static void Main (string[] args) {
list<string> names = new arraylist< String> ();
Names.add ("Beibei");
Names.add ("Jingjing");
foreach for
(String name:names) {
name = ' Huanhuan ';
}
System.out.println (Arrays.tostring (Names.toarray ()));
for for (int i = 0; i < names.size (); i++) {
Names.set (i, "Huanhuan");
}
System.out.println (Arrays.tostring (Names.toarray ()));
}
Output:
[Beibei, Jingjing]
[Huanhuan, Huanhuan]
Special attention to the place!!
The above in-depth understanding of the Java for and foreach Loop is a small series to share all the content, hope to give you a reference, but also hope that we support the cloud habitat community.