2012-10-10 66 views
0

我正在使用HashSet,它具有用於所有元素的一些屬性,然後將此Hashset添加到對應於每個元素的HashMap。另外,爲特定元素添加了很少的屬性(例如THEAD)。HashSet值計算錯誤

但是後面添加的屬性對齊對於表和THEAD都存在。下面的代碼有什麼問題嗎?

private static HashMap<String, Set<String>> ELEMENT_ATTRIBUTE_MAP = 
     new HashMap<String, Set<String>>(); 

HashSet<String> tableSet = 
      new HashSet<String>(Arrays.asList(new String[] 
      {HTMLAttributeName.style.toString(), 
      HTMLAttributeName.color.toString(), 
      HTMLAttributeName.dir.toString(), 
      HTMLAttributeName.bgColor.toString()})); 

ELEMENT_ATTRIBUTE_MAP.put(HTMLElementName.TABLE, new HashSet<String>(tableSet)); 

// Add align only for Head 
tableSet.add(HTMLAttributeName.align.toString()); 

ELEMENT_ATTRIBUTE_MAP.put(HTMLElementName.THEAD, tableSet); 
+0

是什麼問題? –

+0

我不希望對齊屬性是HashSet對應表的一部分。 – Sriharsha

回答

1

您的代碼應該按照您的預期工作。考慮以下(簡體)例子顯示了行爲:

public static void main(String[] args) { 
    String[] array = new String[] {"a", "b", "c"}; 
    HashSet<String> strings = new HashSet(Arrays.asList(array)); 

    Map<String, Set<String>> map = new HashMap(); 
    Map<String, Set<String>> newMap = new HashMap(); 
    Map<String, Set<String>> cloneMap = new HashMap(); 

    map.put("key", strings); 
    newMap.put("key", new HashSet(strings)); 
    cloneMap.put("key", (Set<String>) strings.clone()); 

    strings.add("E"); 

    System.out.println(map); //{key=[E, b, c, a]} 
    System.out.println(newMap); //{key=[b, c, a]} 
    System.out.println(cloneMap); //{key=[b, c, a]} 

} 

注意,Java的變量是對對象的引用,而不是對象本身,所以當你調用map.put("key", strings)它是底層HashSet傳遞一個參考;因此當您稍後更新HashSet時,HashMap也會更新。