总结:1.利用get(indexof)使用普通for循环遍历;2.使用增强for循环进行遍历(低层用iterator实现的);3.使用iterator进行遍历
- 使用iterator遍历ArrayList的时候,遍历顺序是按照数组下标从小到大依次遍历
- 使用iterator遍历LinkedList的时候,遍历顺序是按照链表结构从头到尾依次遍历
for (int i = 0; i < list.size(); i++) {
ObjectName s = (ObjectName)list.get(i);
System.out.println(s.getx()+" "+s.getxx()+" "+s.getxxx());
}
for (ObjectName s : list) {
System.out.println(s.getx()+" "+s.getxx()+" "+s.getxxx());
}
Iterator<ObjectName> iter = list.iterator();
while (iter.hasNext()) {
ObjectName s = (ObjectName) iter.next();
System.out.println(s.getx()+" "+s.getxx()+" "+s.getxxx());
}
总结:1. 使用增强for;2. 使用iterator进行遍历。(注意不能用普通for进行遍历,因为set集合没有顺序概念,所以没有get(indexof)方法)
- 使用iterator遍历TreeSet时,遍历顺序是树的中序遍历(即按照元素从小到大依次遍历)
- 使用iterator遍历HashSet时,遍历顺序是:按照数组下标从小到大进入桶内,如果桶是红黑树结构则按照树的中序遍历输出,如果桶是链表则按照从头到尾的顺序遍历。
for (Object obj : stuSet) {
StudentDemo sDemo = (StudentDemo)obj;
System.out.println("姓名:"+sDemo.getStuName()+"-学号:"+
sDemo.getStuId()+"-成绩:"+sDemo.getStuGrade());
}
Iterator iterator = stuSet.iterator();
while (iterator.hasNext()) {
StudentDemo stuIt = (StudentDemo)iterator.next();
System.out.println("姓名:"+stuIt.getStuName()+"-学号:"+
stuIt.getStuId()+"-成绩:"+stuIt.getStuGrade());
}
总结:
iterator遍历顺序和上述Set遍历顺序一样。
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
//遍历map中的键
for (Integer key : map.keySet()) {
System.out.println("Key = " + key);
}
//遍历map中的值
for (Integer value : map.values()) {
System.out.println("Value = " + value);
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
for (Integer key : map.keySet()) {
Integer value = map.get(key);
System.out.println("Key = " + key + ", Value = " + value);
}
Map<Integer, Integer> map = new HashMap<Integer, Integer>();
Iterator<Map.Entry<Integer, Integer>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<Integer, Integer> entry = entries.next();
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
}