Home > Java > javaTutorial > Foreach usage example in java program

Foreach usage example in java program

高洛峰
Release: 2017-01-21 15:55:25
Original
1552 people have browsed it

Syntax

for (Object objectname : preArrayList(一个Object对象的列表)) {}
Copy after login

Example

package com.kuaff.jdk5;
import java.util.*;
import java.util.Collection;
public class Foreach
{
private Collection c = null;
private String[] belle = new String[4];
public Foreach()
{
belle[0] = "西施";
belle[1] = "王昭君";
belle[2] = "貂禅";
belle[3] = "杨贵妃";
   c = Arrays.asList(belle);
}
public void testCollection()
{
for (String b : c)
{
 System.out.println("曾经的风化绝代:" + b);
}
}
public void testArray()
{
for (String b : belle)
{
  System.out.println("曾经的青史留名:" + b);
}
}
public static void main(String[] args)
{
Foreach each = new Foreach();
   each.testCollection();
each.testArray();
}
}
Copy after login

For both collection types and array types, we can access it through foreach syntax. In the above example, we had to access the array sequentially before, which was quite troublesome:

for (int i = 0; i < belle.length; i++)
{
String b = belle[i];
System.out.println("曾经的风化绝代:" + b);
}
Copy after login

Now we only need the following simple statement:

for (String b : belle)
{
   System.out.println("曾经的青史留名:" + b);
 }
Copy after login

The effect of accessing the collection is more obvious. In the past, our code for accessing the collection:

for (Iterator it = c.iterator(); it.hasNext();)
{
String name = (String) it.next();
System.out.println("曾经的风化绝代:" + name);
}
Copy after login

Now we only need the following statement:

for (String b : c)
{
System.out.println("曾经的风化绝代:" + b);
}
Copy after login

Foreach is not omnipotent, it also has the following shortcomings:

In the previous In the code, we can perform the remove operation through Iterator.

for (Iterator it = c.iterator(); it.hasNext();)
{
   itremove()
}
Copy after login

However, in the current foreach version, we cannot delete the objects contained in the collection. You can't replace objects either.

At the same time, you cannot foreach multiple collections in parallel. Therefore, when we write code, we have to use it according to the situation.

For more articles related to foreach usage examples in java programs, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template