Difference: 1. foreach is more efficient when the number of loops is unknown or it is troublesome to calculate the number of loops, while for is more efficient in more complex loops; 2. foreach is not supported in loops When adding and deleting operations, the array or collection cannot be modified, but the for loop can.
Related recommendations: "Java Video Tutorial"
First of all, let’s talk about foreach, which is also called enhancement. for loop, foreach is actually a special simplified version of the for loop.
Let’s talk about the writing format of foreach:
for(元素类型 元素名称 : 遍历数组(集合)(或者能进行迭代的)){ 语句 }
Although foreach is a simplified version of the for loop, it does not mean that foreach is more powerful than for. It is easy to use. Foreach is more efficient when the number of loops is unknown or it is troublesome to calculate the number of loops. However, some more complex loops still need to use for loops to be more efficient.
Let’s take a 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, it is a little troublesome for us to use a for loop 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 and deleting operations in a loop, because when using foreach When looping, the array (collection) has been locked and cannot be modified, otherwise 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进行添加 } }
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 What is the difference between for and foreach in java?. For more information, please follow other related articles on the PHP Chinese website!

Using POI library in Java to add borders to Excel files Many Java developers are using Apache...

Efficient processing of batch interface requests: Using CompletableFuture to ensure that concurrent calls to third-party interfaces can significantly improve efficiency when processing large amounts of data. �...

In JavaWeb applications, the feasibility of implementing entity-class caching in Dao layer When developing JavaWeb applications, performance optimization has always been the focus of developers. Either...

The current status of motorcycle and motorcycle systems and ecological development of motorcycle systems, as an important bridge connecting knights and vehicles, has developed rapidly in recent years. Many car friends...

When using MyBatis-Plus or tk.mybatis...

How to query personnel data through natural language processing? In modern data processing, how to efficiently query personnel data is a common and important requirement. ...

In processing next-auth generated JWT...

In IntelliJ...


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

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

Hot Article

Hot Tools

SublimeText3 Linux new version
SublimeText3 Linux latest version

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.

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