java中foreach的使用

來源:互聯網
上載者:User
java中foreach的使用

 

Java5之後新增了foreach文法,可以看成for迴圈的一個擴充,其主要用處在於使得遍曆數組或者其他集合(collections)更為方便。這個新文法命名為enhanced for或者foreeach(參考其他語言的命名方式)。

foreach可用於遍曆數組和Collections中每一個連續的值。當然它也可以用於遍曆那些已經實現了Iterable<E>
的介面的對象(需要定義iterator()函數),而許多Collections類都已經實現了Iterable<E>,這使得
foreach文法用了用武之地。

通用格式

以下列出foreach和for的使用形式,同時給出兩個基本的對等式,區別在於是數組還是其他可迭代對象。

例子-計算數組中各元素和

foreach文法實現:

?
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文法的實現:

?
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];}

何時使用foreach合適

從上方例子中可以看出,foreach有些時候能夠使得代碼變得乾淨,但是需要注意某些情況寫不合適:

  1. 唯讀:訪問的元素不能被賦值,比如元素的自增等
  2. 單一結構:不可能同時遍曆兩個結構,比如比較兩個數組
  3. 單一元素:只適合單一的元素讀取
  4. 單向:只能向前單個元素的迭代
  5. 需java5支援:不要在java5前使用該文法

二維數組中foreach的使用

舉例:

?
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();        
}    
}}

foreach更多運用

前面已經說了foreach適用於遍曆數組或者Collections等實現了Iterable<T>介面的對象。例如遍曆List或者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);    
}}

Collections的遍曆如下:

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

其實在編譯的時候,編譯器會把foreach展開,比如上面的Collections展開如下:

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

 

轉載自: http://www.leyond.info/usage-of-foreach-in-java/#more-131521

 

更多關於foreach的神秘資料,

 

參考:http://caterpillar.onlyfun.net/Gossip/JavaEssence/Foreach.html
,本文還參考了:

  1. http://yczhuang.blogspot.com/2009/02/javaforeach.html
  2. http://leepoint.net/notes-java/flow/loops/foreach.html
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.