Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the difference between for and foreach in Java

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

This article mainly explains "what is the difference between for and foreach in Java". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn "what is the difference between for and foreach in Java?"

(1) traversing elements

First of all, let's take each piece of code as an example:

String [] array = {"1", "2", "3"}; for (String I: array) {System.out.println (I);} ArrayList list = new ArrayList (); list.add ("111"); list.add (" 222"); list.add ("333") For (String I: list) {System.out.println (I);}

The result after traversal is as follows:

one

two

three

one hundred and eleven

two hundred and twenty two

three hundred and thirty three

There is no doubt about the result.

Let's take a look at the compiled source code (idea comes with it, just open your class source file in the target package):

String [] array = new String [] {"1", "2", "3"}; String [] var2 = array; int var3 = array.length; for (int var4 = 0; var4 < var3; + + var4) {String I = var2 [var4]; System.out.println (I);} ArrayList list = new ArrayList (); list.add List.add; list.add (333); Iterator var7 = list.iterator (); while (var7.hasNext ()) {String I = (String) var7.next (); System.out.println (I);}

As you can see, the traversal array uses the original for loop, and the collection uses the Iterator iterator.

(2) Delete elements

Oh, k! Next, let's delete the element:

Use a for loop:

ArrayList list = new ArrayList (); list.add; list.add; list.add (333); log.info (list.toString ()); for (int I = 0; I

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report