A brief analysis of java's foreach loop
Jan 21, 2017 pm 03:57 PMWhen using the foreach loop to traverse arrays and collections, there is no need to obtain the length of the array and collection, and there is no need to access array elements and collection elements according to the index. The foreach loop automatically traverses each element of the array and collection.
foreach的语句格式: for(type variableName : array|connection){ //variable自动迭代访问每一个元素 }
Example:
public class ForEachTest { public static void main(String[] args) { String[] books = {"java","c","c++","c#","asp"}; for(String book : books) { System.out.println(book); } } }
Output:
java
c
c++
c
#asp
public class ForEachTest { public static void main(String[] args) { String[] books = {"java","c","c++","c#","asp"}; for(String book : books) { book = "hello world!"; System.out.println(book); } System.out.println(books[0]); } }
Output:
hello world!
hello world!
hello world!
hello world!
hello world!
java
So foreach loops are generally only suitable for array traversal, data extraction and display, etc., and are not suitable for complex operations such as adding, deleting, and using subscripts.
The foreach statement is an enhanced version of the for statement under special circumstances, which simplifies programming and improves the readability and safety of the code (you don’t have to worry about the array going out of bounds). It is a good supplement to the old for statement.
It is recommended that foreach should not be used where foreach can be used. When using a collection or array index, foreach seems to be unable to do its job. At this time, it is time to use the for statement. foreach is generally used in conjunction with generics
For more articles related to a brief analysis of java's foreach loop, please pay attention to the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Top 4 JavaScript Frameworks in 2025: React, Angular, Vue, Svelte

How does Java's classloading mechanism work, including different classloaders and their delegation models?

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?

Node.js 20: Key Performance Boosts and New Features

Iceberg: The Future of Data Lake Tables

Spring Boot SnakeYAML 2.0 CVE-2022-1471 Issue Fixed

How can I implement functional programming techniques in Java?

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?
