怎樣遍歷Collection中的集合如Set

當集合中還有集合時,應該怎樣遍歷呢?這個問題讓我琢磨了一個下午,最後終於有了答案。 java

當咱們使用以下的方法遍歷集合時就會陷入到死循環中,一直打印下去,爲何呢?由於每執行完一次打印,從新執行while語句時又會建立新的iterator,因此這樣的寫法是錯誤的。 spa


Collection<Set<String>> col = new ArrayList<HashSet<String>>;
while(col.iterator.next.iterator.hasNext()){
    System.out.println(col.iterator.next.iterator.next());
}

正確的遍歷方法是先獲取iterator的引用,而後經過這個引用進行遍歷。 code

Iterator it = col.iterator();
while (it.hasNext()) {
   Set<String> set = (Set<String>) it.next();
   Iterator i = set.iterator();
   while (i.hasNext()) {
       System.out.println(i.next());
   }
}
這樣纔可以正確地打印。
相關文章
相關標籤/搜索