【Java-27】容器資料的遍歷——迭代器
阿新 • • 發佈:2019-01-13
1.Set、List的遍歷
public class mySet { public static void main(String[] args) { Set set=new HashSet(); set.add(new student("小花",27)); set.add(new student("小剛",25)); set.add(new student("小民",24)); set.add(new student("小明",23)); Iterator iter=set.iterator(); String str; while(iter.hasNext()){ str=((student)iter.next()).name; System.out.println(str); } // System.out.println(set.size()); } } class student1{ String name; int id; public student1(String name, int id) { super(); this.name = name; this.id = id; } }
2.Map的遍歷
Set set = map.keySet();
Iterator iter = set.iterator();
while(iter.hasNext()){
System.out.println(((student)iter.next()).name);//打印出map中的鍵(1,2,3)
}