2012-10-10 58 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也会更新。