在java中集合的遍历是怎样遍历的

如题所述

List<String> list = new ArrayList<String>();
list.add("aaa");
list.add("bbb");
list.add("ccc");
方法一:
for(String attribute : list) {
System.out.println(attribute);
}
方法二:
for(int i = 0 ; i < list.size() ; i++) {
system.out.println(list.get(i));
}
方法三:
Iterator it = list.iterator();
while(it.hasNext()) {
System.ou.println(it.next);
}
温馨提示:内容为网友见解,仅供参考
第1个回答  2013-11-26
可以使用for或foreach进行遍历
for可以遍历,也可以通过遍历改变值
foreach只是遍历,不会改变值
通常使用foreach比较方便
第2个回答  2013-11-26
//example1:

int[][] array=new int[5][6];
for(int i=0;i<5;i++)
for(int j=0;j<6;j++)
System.out.println(array[i][j]);
...
//example2:

int[][] array={{1,2,3},{5,6},{7,8,9,10,11}};
for(int i=0;i<array.length;i++)
for(int j=0;j<array[i].length;j++)
System.out.println(array[i][j]);
....
这个是二维数组
第3个回答  2013-11-26
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
//集合遍历
public class TestHashSet{
public static void main(String[] args) {
HashSet h = new HashSet();
h.add("1st");
h.add("2nd");
h.add(new Integer(3));
h.add(new Double(4.0));
h.add("2nd"); // 重复元素, 未被加入
h.add(new Integer(3)); // 重复元素,未被加入
h.add(new Date());
System.out.println("开始: size=" + h.size());
Iterator it = h.iterator();
while(it.hasNext()){
Object o = it.next();
System.out.println(o);
}
}
}
相似回答