search
HomeJavajavaTutorialThe most comprehensive summary of the usage of for loop, a new feature of Java

1. Enhanced for overview

Enhanced for loop, also called Foreach loop, is used for traversing arrays and containers (collection classes). When using a foreach loop to traverse array and collection elements, there is no need to obtain the array and collection lengths, and there is no need to access array elements and collection elements based on indexes, which greatly improves efficiency and makes the code much simpler.

2. Explanation from Oracle’s official website

So when should you use a for-each loop? Any time is fine. This really beautifies your code. Unfortunately, you can't use it everywhere. Consider these cases, for example, removing methods. In order to remove the current element, the program needs access to the iterator. The for-each loop hides the iterator, so you can't call the delete function. Therefore, the for-each loop does not work for filtering elements. Loops that require replacing elements when iterating over a collection or array are also not applicable. Finally, it is not suitable for use in parallel loops across multiple collection iterations. Designers should be aware of these pitfalls and consciously design a clean, simple structure to avoid these situations. If you are interested, you can view the API on 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. Enhanced for format

for(集合或者数组元素的类型 变量名 : 集合对象或者数组对象){
 
引用变量名的java语句;
 
}

When you see the colon (:), it reads as "come in." The above loop reads as "traverse each TimerTask element in c. "As you can see, the for-each construct combines perfectly with generics. It retains all types of security 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 has already done it behind your back, you don’t need to care about it.)


Simple experience:

1. Enhance for to traverse the array

package cn.jason01;
//增强for遍历数组
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) {
 // 泛型推断,后面可以写可以不写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;
 
/**
 * 增强for底层原理
 *
 * @author cassandra
 * @version 1.1
 */
public class ForTest {
    public static void main(String[] args) {
        // 泛型推断,后面可以写可以不写String.规范一些是要写上的。
        ArrayList<String> array = new ArrayList();
        // 添加元素
        array.add("a");
        array.add("b");
        array.add("c");
 
        // 增强for实现
        System.out.println("----enhanced for----");
        for (String string : array) {
            System.out.println(string);
        }
 
        // 反编译之后的效果,也就是底层实现原理
        System.out.println("---reverse compile---");
        String string;
        for (Iterator iterator = array.iterator(); iterator.hasNext(); System.out.println(string)) {
            string = (String) iterator.next();
 
        }
 
        // 迭代器实现
        System.out.println("------Iterator------");
        for (Iterator<String> i = array.iterator(); i.hasNext(); System.out.println(i.next())) {
 
        }
 
        // 普通for实现
        System.out.println("-----general for-----");
        for (int x = 0; x < array.size(); x++) {
            System.out.println(array.get(x));
        }
    }
}

As can be seen from the above code, the bottom layer is implemented by iterators. Enhanced for actually hides the iterators, so there is no need to create iterators and the code is much simpler. This is also the reason for the introduction of enhanced for, which is to reduce code, facilitate traversal of collections and arrays, and improve efficiency.

Note: Because enhanced for hides the iterator, when using enhanced for to traverse 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 bottom layer needs to use an array or collection object to call the iterator() method to create an iterator (Iterator is an interface, so it must be implemented by a subclass). If it is null, an exception will definitely be thrown.

5. Enhance the applicability and limitations of for

1. Applicability

Applicable to traversal of collections and arrays.

2. Limitations:

①The collection cannot be null because the underlying layer is an iterator.

②The iterator is hidden, so the collection cannot be modified (added or deleted) when traversing the collection.

③The corner mark cannot be set.

6. Detailed explanation of enhanced for usage

1. Enhanced for usage in arrays

package cn.jason05;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * 增强for用法
 *
 * @author cassandra
 */
public class ForDemo {
 public static void main(String[] args) {
 // 遍历数组
 int[] arr = { 1, 2, 3, 4, 5 };
 for (int x : arr) {
 System.out.println(x);
 }
 }
}

2. Enhanced for usage in collections

package cn.jason05;
 
import java.util.ArrayList;
import java.util.List;
 
/**
 * 增强for用法
 *
 * @author cassandra
 */
public class ForDemo {
 public static void main(String[] args) {
 // 遍历集合
 ArrayList<String> array = new ArrayList<String>();
 array.add("hello");
 array.add("world");
 array.add("java");
 
 for (String s : array) {
 System.out.println(s);
 }
 
 // 集合为null,抛出NullPointerException空指针异常
 List<String> list = null;
 if (list != null) {
 for (String s : list) {
 System.out.println(s);
 }
 }
 
 // 增强for中添加或修改元素,抛出ConcurrentModificationException并发修改异常
 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 combined with generics, otherwise you have to manually transform downward

1. There is no generic effect and the enhanced for

Student class cannot be used

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) {
 // 创建集合1
 List list1 = new ArrayList();
 list1.add("a");
 list1.add("b");
 list1.add("c");
 
 // 创建集合2
 List list2 = new ArrayList();
 list2.add("d");
 list2.add("e");
 list2.add("f");
 // 创建集合三
 List list3 = new ArrayList();
 
 // 遍历第一和第二个集合,并添加元素到集合三
 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));
 }
 }
 
 // 遍历集合三,并输出元素
 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 you remove the two lines of commented code in the above code, the program will report an error, because the collection does not declare the type of the element, and the iterator naturally does not know what type it is. Therefore, if there are no generics, then downward transformation is required. Only iterators can be used, and enhanced for cannot be used.

2. Generics and enhancement for

Generic modification of the above code

package cn.jason01;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
 
/**
 * 增强for和泛型完美结合
 *
 * @author cassandra
 */
public class Test03 {
 public static void main(String[] args) {
 // 创建集合1
 List<String> list1 = new ArrayList<String>();
 list1.add("a");
 list1.add("b");
 list1.add("c");
 
 // 创建集合2
 List<String> list2 = new ArrayList<String>();
 list2.add("d");
 list2.add("e");
 list2.add("f");
 // 创建集合三
 List<Student> list3 = new ArrayList<Student>();
 
 //// 遍历第一和第二个集合,并添加元素到集合三
 for (String s1 : list1) {
 for (String s2 : list2) {
 list3.add(new Student(s1, s2));
 }
 }
 
 // 遍历集合三,并输出元素
 for (Student st : list3) {
 System.out.println(new StringBuilder().append(st.getName1()).append(st.getName2()));
 }
 }
}

4. Four methods for List collection traversal

## There is an iterator() method in the #Collection interface, which returns an Iterator type. There is an iterator called Iterator. There is a listIterator() method in List, so there is an additional collector ListIterator. Its subclasses LinkedList, ArrayList, and Vector all implement the List and Collection interfaces, so they can be traversed using two iterators.

Code test

package cn.jason05;
 
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
 
/**
 * 这是List集合遍历四种方法
 *
 * @author cassandra
 */
 
public class ForDemo01 {
 public static void main(String[] args) {
 // 创建集合
 List<String> list = new ArrayList<String>();
 list.add("hello");
 list.add("world");
 list.add("java");
 
 // 方法1,Iterator迭代器遍历
 Iterator<String> i = list.iterator();
 while (i.hasNext()) {
 String s = i.next();
 System.out.println(s);
 }
 
 // 方法2,ListIterator迭代器遍历集合
 ListIterator<String> lt = list.listIterator();
 while (lt.hasNext()) {
 String ss = lt.next();
 System.out.println(ss);
 }
 
 // 方法3,普通for遍历集合
 for (int x = 0; x < list.size(); x++) {
 String sss = list.get(x);
 System.out.println(sss);
 }
 
 // 方法4,增强for遍历集合
 for (String ssss : list) {
 System.out.println(ssss);
 }
 
 }
}

5.Set collection traversal method in 2

Since the Set collection does not have get(int index) method, so there is no ordinary for loop, there is no listIterator() method in Set, so there is no ListIterator iterator. So there are only two ways to traverse.

Code Test

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");
 
 // 方法1,Iterator迭代器遍历集合
 Iterator<String> it = set.iterator();
 while (it.hasNext()) {
 System.out.println(it.next());
 }
 
 // 方法2,增强for遍历集合
 for (String s : set) {
 System.out.println(s);
 }
 
 }
}

7. Summary

1. Enhance the applicability and limitations of for

Applicability: Suitable for traversal of collections and arrays.

Limitations:

①The collection cannot be null because the underlying layer is an iterator.

②The corner mark cannot be set.

③The iterator is hidden, so the collection cannot be modified (added or deleted) when traversing the collection.

2. Only by enhancing the combination of for and generics in the collection can new features be brought into play.

3. It is very important to check the new features of the official website. To know what they are, you also need to know why. Only when you understand them in your mind can you use them freely.

The above summary of the most complete usage of the for loop, a new feature of Java, is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more java new features, the most complete usage summary of the for loop, please pay attention to the PHP Chinese website for related articles!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Explain how the JVM acts as an intermediary between the Java code and the underlying operating system.Apr 29, 2025 am 12:23 AM

JVM works by converting Java code into machine code and managing resources. 1) Class loading: Load the .class file into memory. 2) Runtime data area: manage memory area. 3) Execution engine: interpret or compile execution bytecode. 4) Local method interface: interact with the operating system through JNI.

Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Explain the role of the Java Virtual Machine (JVM) in Java's platform independence.Apr 29, 2025 am 12:21 AM

JVM enables Java to run across platforms. 1) JVM loads, validates and executes bytecode. 2) JVM's work includes class loading, bytecode verification, interpretation execution and memory management. 3) JVM supports advanced features such as dynamic class loading and reflection.

What steps would you take to ensure a Java application runs correctly on different operating systems?What steps would you take to ensure a Java application runs correctly on different operating systems?Apr 29, 2025 am 12:11 AM

Java applications can run on different operating systems through the following steps: 1) Use File or Paths class to process file paths; 2) Set and obtain environment variables through System.getenv(); 3) Use Maven or Gradle to manage dependencies and test. Java's cross-platform capabilities rely on the JVM's abstraction layer, but still require manual handling of certain operating system-specific features.

Are there any areas where Java requires platform-specific configuration or tuning?Are there any areas where Java requires platform-specific configuration or tuning?Apr 29, 2025 am 12:11 AM

Java requires specific configuration and tuning on different platforms. 1) Adjust JVM parameters, such as -Xms and -Xmx to set the heap size. 2) Choose the appropriate garbage collection strategy, such as ParallelGC or G1GC. 3) Configure the Native library to adapt to different platforms. These measures can enable Java applications to perform best in various environments.

What are some tools or libraries that can help you address platform-specific challenges in Java development?What are some tools or libraries that can help you address platform-specific challenges in Java development?Apr 29, 2025 am 12:01 AM

OSGi,ApacheCommonsLang,JNA,andJVMoptionsareeffectiveforhandlingplatform-specificchallengesinJava.1)OSGimanagesdependenciesandisolatescomponents.2)ApacheCommonsLangprovidesutilityfunctions.3)JNAallowscallingnativecode.4)JVMoptionstweakapplicationbehav

How does the JVM manage garbage collection across different platforms?How does the JVM manage garbage collection across different platforms?Apr 28, 2025 am 12:23 AM

JVMmanagesgarbagecollectionacrossplatformseffectivelybyusingagenerationalapproachandadaptingtoOSandhardwaredifferences.ItemploysvariouscollectorslikeSerial,Parallel,CMS,andG1,eachsuitedfordifferentscenarios.Performancecanbetunedwithflagslike-XX:NewRa

Why can Java code run on different operating systems without modification?Why can Java code run on different operating systems without modification?Apr 28, 2025 am 12:14 AM

Java code can run on different operating systems without modification, because Java's "write once, run everywhere" philosophy is implemented by Java virtual machine (JVM). As the intermediary between the compiled Java bytecode and the operating system, the JVM translates the bytecode into specific machine instructions to ensure that the program can run independently on any platform with JVM installed.

Describe the process of compiling and executing a Java program, highlighting platform independence.Describe the process of compiling and executing a Java program, highlighting platform independence.Apr 28, 2025 am 12:08 AM

The compilation and execution of Java programs achieve platform independence through bytecode and JVM. 1) Write Java source code and compile it into bytecode. 2) Use JVM to execute bytecode on any platform to ensure the code runs across platforms.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment