2014-12-05 31 views
2
Set<String> set = new HashSet<String>() { 
     public boolean add(String arg0) { 
      if (arg0 == null) { 
       throw new IllegalArgumentException("Cannot add null to Set"); 
      } 

      return super.add(arg0); 
     } 
    }; 

    set.add("s0"); 

    Set<String> toAdd = new HashSet<String>(); 
    toAdd.add("s1"); 
    toAdd.add("s2"); 
    toAdd.add(null); 
    toAdd.add("s4"); 
    toAdd.add("s5"); 

    try { 
     set.addAll(toAdd); 
    } catch (IllegalArgumentException e) { 
     e.printStackTrace(); 
    } 

    System.out.println(set.toString()); 

這是我的代碼。我創建了一個HashSet,您不能添加null,否則您將得到IllegalArgumentException。然後,我將String"s0"添加到HashSet,並且我創建了另一個HashSet以使用addAll()測試我的代碼,因爲addAll()使用了add()方法。addAll()中異常後仍爲空HashSet

輸出代碼:

java.lang.IllegalArgumentException: Cannot add null to Set 
    at testprogramm.TestProgramm$1.add(TestProgramm.java:17) 
    at testprogramm.TestProgramm$1.add(TestProgramm.java:1) 
    at java.util.AbstractCollection.addAll(Unknown Source) 
    at testprogramm.TestProgramm.main(TestProgramm.java:39) 
[s0] 

正如你可以看到有按計劃的IllegalArgumentException但爲什麼會出現連一個也沒有StringsetHashSettoAddHashSet的? setHashSet中的所有字符串是否不應與toAddHashSet中空元素的「索引」較低有關?

+0

'HashSet'沒有訂單,所以沒有人指數「。 – Biffen 2014-12-05 17:00:15

+0

是的,但必須有一種添加字符串的順序,所以在該集合中應該有像「s1」或「s2」這樣的字符串。 – stonar96 2014-12-05 17:01:52

+2

我敢打賭,null值總是迭代器返回的第一個值。 – 2014-12-05 17:02:57

回答

3

如果您將空值添加到HashSet迭代器將返回空值作爲第一個元素。這就是爲什麼你只能看到第一個元素[s0]。你可以打印添加並測試它(System.out.println(toAdd.toString()))

+0

謝謝你的回答。 – stonar96 2014-12-05 17:14:11

1

addAll(Collection)是java.util.AbstractCollection的方法,它不捕獲任何異常。 當HashSet傳遞第一個元素爲null時。對於第一個空元素執行迭代,因爲該執行

throws IllegalArgumentException("Cannot add null to Set") 

因此不再發生迭代。沒有元素被添加。

中的addAll方法的詳細信息:

public boolean addAll(Collection<? extends E> c) { 
    boolean modified = false; 
    Iterator<? extends E> e = c.iterator(); 
    while (e.hasNext()) { 
     if (add(e.next())) 
      modified = true; 
    } 
    return modified; 
} 

http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/AbstractCollection.java#AbstractCollection.addAll%28java.util.Collection%29