The following editor will bring you a cliché about the difference between foreach (enhanced for loop) and for. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.
First of all, let’s talk about foreach, which is also called enhanced for loop. Foreach is actually a special simplified version of for loop.
Let’s talk about the writing format of foreach:
for (element type element name: traverse array (set) (or iterable) ) {
Statement
}
Although foreach is a simplified version of the for loop, it does not mean that foreach is more useful than for. foreach is suitable for unknown loop times. Or it may be more efficient when calculating the number of loops is troublesome, but more complex loops still need to use for loops, which are more efficient.
Let’s look at the following example:
public static void main(String[] args) { List<String> arr = new ArrayList<String>(); arr.add("你好"); arr.add("我好"); arr.add("大家好"); //foreach循环 for(String str : arr){ //这里的str就是为了获取每次循环的arr中的值 System.out.println(str); //就相当于 String str=arr[i] } }
But in comparison we use a for loop It’s a little troublesome to input
public static void main(String[] args) { List<String> arr = new ArrayList<String>(); arr.add("你好"); arr.add("我好"); arr.add("大家好"); //for循环 for(int i=0;i<arr.size();i++){ System.out.println(arr.get(i)); //要获取list中元素需要用get方法 } }
In addition to this ordinary collection, you can also use key-value pairs like map
For example:
public static void main(String[] args) { Map<String,String> mapstr = new HashMap<String,String>(); mapstr.put("王", "男"); mapstr.put("李", "男"); mapstr.put("张", "女"); //entrySet方法是为了获取键值对的集合 for(Map.Entry<String, String> s : mapstr.entrySet()){ //这里的Map.Entry<String, String>其实就是一个类型 用来表示键值对的类型 System.out.println("key="+s.getKey()); //这里其实还是相当于 s=maostr.entrySet,只不过s存储的是键值对。 System.out.println("value="+s.getValue()); //所以可以用get方法获取出来存储的键值对。 } }
In addition, foreach does not support adding deletion operations in the loop, because when using the foreach loop, the array (collection) has been locked and cannot be modified, otherwise it will report java .util.ConcurrentModificationExceptionException
For example:
public static void main(String[] args) { List<String> arr = new ArrayList<String>(); arr.add("你好"); arr.add("我好"); arr.add("大家好"); //foreach循环 for(String str : arr){ System.out.println(str); arr.add("1"); //对arr进行添加 } }
We will talk about the principle of not being able to add and delete and how to add and delete in foreach in the next article.
So the summary is as follows:
foreach is suitable for just traversing a collection or array, while for is more efficient in more complex loops.
Foreach cannot modify the array or collection (add or delete operations). If you want to modify it, you must use a for loop.
So the for loop is more flexible in comparison.
The above is the detailed content of Compare the difference between foreach and for. For more information, please follow other related articles on the PHP Chinese website!

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function