1. 程式人生 > >集合Set迭代器遍歷和陣列遍歷

集合Set迭代器遍歷和陣列遍歷

		import java.util.Date;
		import java.util.HashSet;
		import java.util.Iterator;
		import java.util.Set;

		public class IteratorAndArray {

			public static void main(String[] args) {
				Set set = new HashSet();
				
				set.add(new String("abc"));
				set.add(new Date());
				set.add(new Integer(20));
				set.add(null);
				
				//迭代器遍歷
				Iterator it = set.iterator();
				while(it.hasNext()){        //還有下一個嗎?
					Object obj = it.next(); //下一個
					System.out.print(obj + "\t");
					//輸出null	Tue Mar 19 21:12:39 CST 2013 abc 20	
				}
				
				System.out.println();
				//陣列遍歷
				Object[] objs = set.toArray();
				for (int i = 0; i < objs.length; i++) {
					System.out.print(objs[i] + "\t");
					//輸出null	Tue Mar 19 21:12:39 CST 2013 abc 20	
				}

			}

		}