search
HomeJavajavaTutorialCompare the difference between foreach and for

Compare the difference between foreach and for

Sep 05, 2017 pm 02:06 PM
foreachthe differenceCompare

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!

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
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

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

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

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

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

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

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

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]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

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

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function