2016-06-28 85 views
-5

願你講解有關代碼如下聲明:Java集合和等於與==

Collection<String> stringCollection = new HashSet<String>(); 
stringCollection.add(new String ("bye")); 
stringCollection.add(new String ("hi")); 
stringCollection.add(new String ("bye again")); 
for(Iterator<String> iter=stringCollection.iterator(); 
    iter.hasNext();){ 
     String str=iter.next(); 
     if(str.equals("hi")) 
      iter.remove(); 
} 
for (String str: stringCollection){ 
     if(str.equals("hi")) 
       stringCollection.remove("hi"); 
} 
System.out.println(stringCollection.size()); 

如果我們改變這兩個循環的順序,那麼代碼將不出現錯誤和打印2運行: 錯了存在運行時錯誤,但爲什麼它看起來正確?

+1

有3個問這裏非常不同的問題。你能專注於單一嗎?這就是說,請參閱http://stackoverflow.com/questions/223918/iterating-through-a-collection-avoiding-concurrentmodificationexception-when-re for a)和http://stackoverflow.com/questions/14150628/string-常量池-java b)和http://stackoverflow.com/questions/16079931/java-lists-remove-method-works-only-for-second-last-object-inside-for-each-loo for c ) – Tunaki

+0

Tunaki:一個問題:在這個特定的代碼中會發生什麼,命令是否重要,並且「平等」? – avivlevi

回答

0

錯誤是由於您在迭代循環中嘗試刪除集合的項目而引起的,因此無論何時在這段代碼中調用remove方法都會引發併發修改異常。

for (String str : stringCollection) { 
    if (str.equals("hi")) 
     stringCollection.remove("hi"); 
} 

之所以沒有錯誤,如果你運行代碼張貼是因爲第一循環中刪除項目「喜」,因此第二循環永遠不會調用stringCollection.remove(...)。

以及由@Tunaki提到這已經說明here