1. Enhanced for overview
Enhanced for loop, also known as Foreach loop, is used to traverse arrays and containers (collection classes). When using foreach to loop through arrays and collection elements, there is no need to obtain the array and collection length, no need to access array elements and collection elements based on the index, which greatly improves efficiency and the code is much simpler.
2. The explanation of Oracle official website
So when should you use the for-each loop? Any time you can. It really beautifuls 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 consciousness 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? It's OK at any time. This really beautifies your code. Unfortunately, you can't use it anywhere. Consider these situations, for example, the deletion method. In order 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, for-each loops are not suitable for filtering elements. Also, loops that need to replace elements when iterating through a collection or array are not applicable. Finally, it is not suitable for parallel loop usage in multiple collection iterations. Designers should understand these flaws and consciously design a clean, simple structure to avoid these situations. If you are interested, you can view the API of the official website. If you don’t know how to find the API on the official website, please click to open the official website to view the API method.
3. Enhance the for format
for (type variable name of collection or array element: collection object or array object) { java statement that references variable name;}Official website explanation:
for (TimerTask t : c)
t.cancel();
When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need Not concern yourself with it.)
The general meaning is:
When you see the colon (:), it reads "Come in." The above loop reads "Traveling every TimerTask element in c." As you can see, the for-each structure is perfectly combined with generics. It retains all types of security while removing the remaining confusion. Because you don't have to declare the iterator, you don't have to provide it with a generic declaration. (The compiler has done it behind you, you don't need to care about it.)
A simple experience:
1. Enhanced for traversal arrays
package cn.jason01;//Enhanced for traversal array public class ForTest01 { public static void main(String[] args) { int[] array={1,2,3}; for(int element: array){ System.out.println(element); } }}2. Enhanced for traversal collections
package cn.jason01;import java.util.ArrayList;public class ForTest { public static void main(String[] args) { // Generic inference, you can write or not to write 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 first
package cn.jason01;import java.util.ArrayList;import java.util.Iterator;/** * Enhanced for the underlying principle* * @author cassandra * @version 1.1 */public class ForTest {public static void main(String[] args) {// Generic inference, you can write later or not. Some specifications need to be written. ArrayList<String> array = new ArrayList();// Add element array.add("a");array.add("b");array.add("c");// Enhance for implementation System.out.println("----enhanced for----");for (String string : array) {System.out.println(string);}// The effect after decompilation, 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 implements System.out.println("------------"); for (Iterator<String> i = array.iterator(); i.hasNext(); System.out.println(i.next()))) {}// Ordinary for implementing System.out.println("-----------"); for (int x = 0; x < array.size(); x++) {System.out.println(array.get(x));}}}From the above code, we can see that the underlying layer is implemented by iterators, and enhancement for actually hides the iterator, so the natural code is much simpler without creating iterators. This is also the reason why Enhancement For is launched, which is to reduce code, facilitate traversing collections and arrays, and improve efficiency.
Note: Because Enhancement for hides iterators, when using Enhancement for traversing collections and arrays, you must first determine whether it is null, otherwise a null pointer exception will be thrown. The reason is very simple. The underlying layer needs to use an array or collection object to call the iterator() method to create an iterator (the Iterator iterator is an interface, so it needs to be implemented with a subclass). If it is null, an exception will definitely be thrown.
5. Enhance the applicability and limitations of for
1. Applicability
Suitable for traversal of collections and arrays.
2. Limitations:
① The set cannot be null because the underlying layer is an iterator.
② The iterator is hidden, so the collection cannot be modified (added and deleted) when traversing the collection.
③Cannot set angle marks.
6. Detailed explanation of the usage of enhancement for
1. Enhanced usage for in arrays
package cn.jason05;import java.util.ArrayList;import java.util.List;/** * Enhanced for usage* * @author cassandra */public class ForDemo { public static void main(String[] args) { // traverse the array int[] arr = { 1, 2, 3, 4, 5 }; for (int x : arr) { System.out.println(x); } }}2. Enhance the usage of for in collections
package cn.jason05;import java.util.ArrayList;import java.util.List;/** * Enhanced 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 set is null, throw a NullPointerException null pointer exception List<String> list = null; if (list != null) { for (String s : list) { System.out.println(s); } } // Enhance the addition or modification of elements in for, throw a ConcurrentModificationException concurrently modified exception for (String x : array) { if (array.contains("java")) array.add(1, "love"); } }3. The perfect combination of generics and enhancement for
Note: It must be perfectly combined with generics, otherwise you have to manually transform downwards.
1. No generic effect, cannot use enhancement for
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; }}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 set 1 List list1 = new ArrayList(); list1.add("a"); list1.add("b"); list1.add("c"); // Create set 2 List list2 = new ArrayList(); list2.add("d"); list2.add("e"); list2.add("f"); // Create set three List list3 = new ArrayList(); // traverse the first and second sets and add elements to set three 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 set three and output the element 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 removes the two lines of the comment, 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 there are no generics, then you need to transform downward, you can only use iterators, not enhancements for.
2. Generics and Enhancements for
Modify the above code
package cn.jason01;import java.util.ArrayList;import java.util.Iterator;import java.util.List;/** * Enhance the perfect combination of for and generics* * @author cassandra */public class Test03 { public static void main(String[] args) { // Create set 1 List<String> list1 = new ArrayList<String>(); list1.add("a"); list1.add("b"); list1.add("c"); // Create set 2 List<String> list2 = new ArrayList<String>(); list2.add("d"); list2.add("e"); list2.add("f"); // Create set three List<Student> list3 = new ArrayList<Student>(); //// traverse the first and second sets and add elements to set three for (String s1 : list1) { for (String s2 : list2) { list3.add(new Student(s1, s2)); } } // traverse the set three and output elements for (Student st : list3) { System.out.println(new StringBuilder().append(st.getName1()).append(st.getName2())); } }}4. Four methods of list collection traversal
There is the iterator() method in the Collection interface, which returns the Iterator type and has an iterator as Iterator. There is a listIterator() method in List, so there is an additional collection ListIterator. Its subclasses LinkedList, ArrayList, and Vector all implement List and Collection interfaces, so you can all use two iterators to traverse.
Code Testing
package cn.jason05;import java.util.ArrayList;import java.util.Iterator;import java.util.List;import java.util.ListIterator;/** * These are four methods of traversing List. * @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"); // Method 1, Iterator iterator traversal Iterator<String> i = list.iterator(); while (i.hasNext()) { String s = i.next(); System.out.println(s); } // Method 2, ListIterator iterator traversal collection ListIterator<String> lt = list.listIterator(); while (lt.hasNext()) { String ss = lt.next(); System.out.println(ss); } // Method 3, Ordinary for traversal collection for (int x = 0; x < list.size(); x++) { String sss = list.get(x); System.out.println(sss); } // Method 4, enhance for traversal collection for (String ssss: list) { System.out.println(sss); } }}5.Set collection traversal method in 2
Since the Set collection does not have a get(int index) method, there is no ordinary for loop, there is no listIterator() method in the Set, so there is no ListIterator iterator. So there are only two ways to traverse.
Code Testing
package cn.jason05;import java.util.HashSet;import java.util.Iterator;import java.util.Set;public class ForTest03 { public static void main(String[] args) { Set<String> set = new HashSet<String>(); set.add("hello"); set.add("world"); set.add("java"); // Method 1, Iterator iterator iterator it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); } // Method 2, enhance for traversal collection for (String s: set) { System.out.println(s); } }}7. Summary
1. Enhance the applicability and limitations of for
Applicability: Applicable to traversals of collections and arrays.
limitation:
① The set cannot be null because the underlying layer is an iterator.
② Angle mark cannot be set.
③The iterator is hidden, so the collection cannot be modified (added and deleted) when traversing the collection.
2. Only by enhancing the combination of for and generics in the collection can the role of new features be played.
3. It is very important to view the new features of the official website. You must know the reason and the reason. Only by knowing it in your heart can you use it freely.
The most complete summary of the usage of the for loop in the above article "Java new features" is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.