foreach格式

for(类型 变量:遍历对象){

访问变量;

}

如下程序:

package com.foreach.test1;

import java.util.ArrayList;
import java.util.List;

public class ForEachTest1 {
public static void main(String args[]) {
ForEachTest1 t1
= new ForEachTest1();
t1.test1();
t1.listTest();
}

public void test1() {
int array1[]={1,2,3,5,4};
for(int x:array1){
System.out.println(
"x=="+x);
}

}
public void listTest(){
List
<String> myList = new ArrayList<String>();
myList.add(
"1");
myList.add(
"4");
myList.add(
"3");
for(String s:myList){
System.out.println(
"s=="+s);
}

Object obj1[]
=myList.toArray();
for(Object o:obj1){
System.out.println(
"o=="+o);
}
}

}

运行结果:

x==1
x==2
x==3
x==5
x==4
s==1
s==4
s==3
o==1
o==4
o==3

posted on 2011-08-16 21:57  snowdrop  阅读(135)  评论(0)    收藏  举报