Use of foreach in Java

Source: Internet
Author: User
Tags iterable
Use of foreach in Java

 

After Java 5, the foreach syntax is added, which can be seen as an extension of the for loop. Its main use is to make it easier to traverse arrays or other collections. The new syntax is named enhanced for or foreeach (refer to the naming method in other languages ).

Foreach can be used to traverse the array and each successive value in collections. Of course, it can also be used to traverse those that have implemented iterable <E>
(Iterator () function must be defined), and many collections classes have implemented iterable <E>, which makes
The foreach syntax is useful.

Common Format

The following lists the use of foreach and for, and provides two basic equivalence types, the difference between arrays and other iteratable objects.

Example-calculate the elements and

Foreach syntax implementation:

?
12345 double
[] ar = {
1.2
,
3.0
,
0.8
};int
sum =
0
;for
(
double
d : ar) { 
// d gets successively each value in ar.    
sum += d;}

For syntax implementation:

?
12345 double
[] ar = {
1.2
,
3.0
,
0.8
};int
sum =
0
;for
(
int
i =
0
; i < ar.length; i++) { 
// i indexes each element successively.    
sum += ar[i];}

When to use foreach

From the example above, we can see that foreach can clean the code sometimes, but note that it is not suitable for writing in some cases:

  1. Read-Only: The accessed element cannot be assigned a value, such as the auto-increment of the element.
  2. Single structure: it is impossible to traverse two structures at the same time, such as comparing two Arrays
  3. Single element: Only applicable to reading a single element
  4. Unidirectional: Only iterations of the previous element can be performed.
  5. Java 5 supported: Do not use this syntax before Java 5

Use of foreach in two-dimensional array

Example:

?
123456789101112131415 public
class
test02 {    
public
static
void
main(String args[])    
{        
int
[][] a =
new
int
[][] {            
{
1
,
2
,
3
,
4
,
5
},            
{
10
,
11
,
12
}        
};          
for
(
int
[] row : a) {            
for
(
int
element : row)                
System.out.print(element +
" "
);            
System.out.println();        
}    
}}

More use of foreach

As mentioned above, foreach applies to objects that implement the iterable <t> interface, such as traversing arrays or collections. For example, traverse list or set:

?
12345678910111213 //Listpublic
void
go(List<String> list) {    
for
(String element : list) {        
System.out.println(element);    
}} //setpublic
void
go(Set<String> set) {    
for
(String element : set) {        
System.out.println(element);    
}}

The traversal of collections is as follows:

?
12345 public
void
go(Collection<String> collection) {    
for
(String element : collection) {        
System.out.println(element);    
}}

In fact, during compilation, the compiler will expand foreach. For example, the preceding collections is expanded as follows:

?
123456 public
void
go(Collection collection) {    
String s;    
for
(Iterator iterator = collection.iterator();        
iterator.hasNext(); System.out.println(s))        
s = (String)iterator.next();}

 

Reprinted from: http://www.leyond.info/usage-of-foreach-in-java/#more-131521

 

For more mysterious information about foreach,

 

Reference: http://caterpillar.onlyfun.net/Gossip/JavaEssence/Foreach.html
, This article also references:

  1. Http://yczhuang.blogspot.com/2009/02/javaforeach.html
  2. Http://leepoint.net/notes-java/flow/loops/foreach.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.