java features the most complete usage summary of the for loop
- 2020-05-26 09:15:24
- OfStack
1. Enhanced for overview
Enhanced for loop, also known as Foreach loop, for array and container (collection class) traversal. When using foreach to loop through groups and collection elements, you don't need to get the array and collection length, and you don't need to access array and collection elements according to the index, which greatly improves the efficiency and the code is much cleaner.
2. Explanation of Oracle website
So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases.
So when should you use the for-each loop? Anytime. It really beautifies your code. Unfortunately, you can't use it anywhere. Consider these cases, for example, the delete method. To remove the current element, the program needs to access the iterator. The for-each loop hides the iterator, so you can't call the delete function. Therefore, the for-each loop does not apply to filter elements. Likewise, loops that need to replace elements when traversing a collection or array are not appropriate. Finally, it is not suitable for parallel looping across multiple collection iterations. Designers should be aware of these defects and consciously design a clean, simple structure to avoid them. If you are interested, you can check API on the official website. If you don't know how to find API on the official website, please click on the official website to find API.
3. Enhanced for format
for( The type of a collection or array element The variable name : Collection object or array object ){
That refers to the variable name java statements ;
}
Official website:
for (TimerTask t : c)
t.cancel();
When you see colon (:) read see the colon (:) read it in in. the for each construct combines beautifully with generics. It preserves all of type type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don have have provide a generic declaration for it compiler does this for behind your your back but you need not concern yourself with it.)
Meaning:
When you see the colon (:), it reads "come in." The above loop reads "traverse each TimerTask element in c." As you can see, the for-each structure works perfectly with generics. It preserves all types of security while removing the rest of the clutter. Because you don't have to declare an iterator, you don't have to provide a generic declaration for it. (the compiler does it behind your back, you don't need to care.)
Simple experience:
1. Enhanced for traversal groups
package cn.jason01;
// To enhance for Through the array
public class ForTest01 {
public static void main(String[] args) {
int[] array={1,2,3};
for(int element: array){
System.out.println(element);
}
}
}
2. Enhance for to traverse the collection
package cn.jason01;
import java.util.ArrayList;
public class ForTest {
public static void main(String[] args) {
// Generic inference, which can be written later or not String
ArrayList<String> array = new ArrayList();
array.add("a");
array.add("b");
array.add("c");
for (String string : array) {
System.out.println(string);
}
}
}
4. Enhance the underlying principle of for
Look at the code
package cn.jason01;
import java.util.ArrayList;
import java.util.Iterator;
/**
* To enhance for The underlying principle
*
* @author cassandra
* @version 1.1
*/
public class ForTest {
public static void main(String[] args) {
// Generic inference, which can be written later or not String. specification 1 Here's something to write.
ArrayList<String> array = new ArrayList();
// Add elements
array.add("a");
array.add("b");
array.add("c");
// To enhance for implementation
System.out.println("----enhanced for----");
for (String string : array) {
System.out.println(string);
}
// The effect after decompiling, that is, the underlying implementation principle
System.out.println("---reverse compile---");
String string;
for (Iterator iterator = array.iterator(); iterator.hasNext(); System.out.println(string)) {
string = (String) iterator.next();
}
// Iterator implementation
System.out.println("------Iterator------");
for (Iterator<String> i = array.iterator(); i.hasNext(); System.out.println(i.next())) {
}
// ordinary for implementation
System.out.println("-----general for-----");
for (int x = 0; x < array.size(); x++) {
System.out.println(array.get(x));
}
}
}
As you can see from the above code, the underlying layer is implemented by the iterator, and the enhanced for actually hides the iterator, so the code is much cleaner without having to create an iterator. This is also the reason for the enhanced for rollout, which is to reduce code, facilitate traversal of collections and arrays, and improve efficiency.
Note: because enhanced for hides iterators, when traversing collections and arrays with enhanced for, you must first determine if it is null, otherwise a null pointer exception will be thrown. The reason is very simple, the underlying need to use an array or collection object to call the iterator() method to create an iterator (Iterator iterator is an interface, so use a subclass), if it is null, you must throw an exception.
5. Enhance the applicability and limitations of for
1. The applicability
For traversal of collections and arrays.
2. Limitations:
The set cannot be null, because the bottom layer is an iterator.
(2) the iterator is hidden, so when traversing the collection can not modify the collection (add or delete).
3. Cannot set corner mark.
6. Enhance the usage of for
1. Enhanced use of for in arrays
package cn.jason05;
import java.util.ArrayList;
import java.util.List;
/**
* To enhance for usage
*
* @author cassandra
*/
public class ForDemo {
public static void main(String[] args) {
// Through the array
int[] arr = { 1, 2, 3, 4, 5 };
for (int x : arr) {
System.out.println(x);
}
}
}
2. Enhanced use of for in collections
package cn.jason05;
import java.util.ArrayList;
import java.util.List;
/**
* To enhance for usage
*
* @author cassandra
*/
public class ForDemo {
public static void main(String[] args) {
// Traverse the collection
ArrayList<String> array = new ArrayList<String>();
array.add("hello");
array.add("world");
array.add("java");
for (String s : array) {
System.out.println(s);
}
// The collection of null Thrown, NullPointerException Null pointer exception
List<String> list = null;
if (list != null) {
for (String s : list) {
System.out.println(s);
}
}
// To enhance for Add or modify elements in, throw ConcurrentModificationException Concurrent modification exception
for (String x : array) {
if (array.contains("java"))
array.add(1, "love");
}
}
3. Perfect combination of generics and enhanced for
Note: it must be perfectly integrated with generics, otherwise it will need to be transformed
1. You cannot use enhanced for without a generic effect
Student class
package cn.jason01;
public class Student {
private String name1;
private String name2;
public Student() {
super();
}
public Student(String name1, String name2) {
super();
this.name1 = name1;
this.name2 = name2;
}
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
}
The test code
package cn.jason01;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Test02 {
public static void main(String[] args) {
// Create a collection 1
List list1 = new ArrayList();
list1.add("a");
list1.add("b");
list1.add("c");
// Create a collection 2
List list2 = new ArrayList();
list2.add("d");
list2.add("e");
list2.add("f");
// Create a collection 3
List list3 = new ArrayList();
// Through the first 1 And the first 2 And add elements to the collection 3
for (Iterator i = list1.iterator(); i.hasNext();) {
// System.out.println(i.next());
String s = (String) i.next();
for (Iterator j = list2.iterator(); j.hasNext();) {
// list2.add(new Student(s,j.next()));
String ss = (String) j.next();
list3.add(new Student(s, ss));
}
}
// Traverse the collection 3 , and output elements
Student st;
for (Iterator k = list3.iterator(); k.hasNext(); System.out
.println(new StringBuilder().append(st.getName1()).append(st.getName2()))) {
st = (Student) k.next();
}
}
}
If the above code leaves out the two lines of commented code, the program will report an error, because the collection does not declare what type the element is, and the iterator naturally does not know what type it is. So if you don't have generics, you're going to have to go down, you're going to have to use iterators, you're not going to use enhanced for.
2. Generics and enhanced for
Generics modify the code above
package cn.jason01;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* To enhance for And generics
*
* @author cassandra
*/
public class Test03 {
public static void main(String[] args) {
// Create a collection 1
List<String> list1 = new ArrayList<String>();
list1.add("a");
list1.add("b");
list1.add("c");
// Create a collection 2
List<String> list2 = new ArrayList<String>();
list2.add("d");
list2.add("e");
list2.add("f");
// Create a collection 3
List<Student> list3 = new ArrayList<Student>();
//// Through the first 1 And the first 2 And add elements to the collection 3
for (String s1 : list1) {
for (String s2 : list2) {
list3.add(new Student(s1, s2));
}
}
// Traverse the collection 3 , and output elements
for (Student st : list3) {
System.out.println(new StringBuilder().append(st.getName1()).append(st.getName2()));
}
}
}
4. The List set traverses four methods
The Collection interface has the iterator() method, which returns the Iterator type, and one iterator is Iterator. List has the listIterator() method, so there is one more aggregator ListIterator. Its subclasses LinkedList, ArrayList and Vector all implement the List and Collection interfaces, so they can all be traversed with two iterators.
The test code
package cn.jason05;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
/**
* This is a List A collection of traverse 4 methods
*
* @author cassandra
*/
public class ForDemo01 {
public static void main(String[] args) {
// Create a collection
List<String> list = new ArrayList<String>();
list.add("hello");
list.add("world");
list.add("java");
// methods 1 . Iterator Iterator traversal
Iterator<String> i = list.iterator();
while (i.hasNext()) {
String s = i.next();
System.out.println(s);
}
// methods 2 . ListIterator The iterator traverses the collection
ListIterator<String> lt = list.listIterator();
while (lt.hasNext()) {
String ss = lt.next();
System.out.println(ss);
}
// methods 3 , ordinary for Traverse the collection
for (int x = 0; x < list.size(); x++) {
String sss = list.get(x);
System.out.println(sss);
}
// methods 4 And enhance the for Traverse the collection
for (String ssss : list) {
System.out.println(ssss);
}
}
}
5.Set set traverses 2 methods
Since there is no get(int index) method in the Set set, there is no normal for loop, and there is no listIterator() method in Set, so there is no ListIterator iterator. So there are only two ways to traverse.
The test code
package cn.jason01;
// To enhance for Through the array
public class ForTest01 {
public static void main(String[] args) {
int[] array={1,2,3};
for(int element: array){
System.out.println(element);
}
}
}
0
7. Summarize
1. Enhance the applicability and limitations of for
Applicability: for traversal of collections and arrays.
Limitations:
The set cannot be null, because the bottom layer is an iterator.
(2) cannot set corner mark.
(3) the iterator is hidden, so the collection cannot be modified (added or deleted) while traversing the collection.
2. Enhance the combination of for and generics in the collection to bring the new features into play.
3. It is very important to check the new features of the official website, and to know the reason why, such as the heart, to use freely.