0

I am using HashSet which has some attributes used for all elements and then adding this Hashset to a HashMap corresponding for each element. Additionally few attributes are added for specific elements( ex THEAD ).

But the later added attribute align is present for both Table and THEAD. Is there something wrong in the below code.

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);
4

1 回答 1

1

Your code should work as you expect. Consider the following (simplified) example which shows the behaviour:

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]}

}

Note that Java variables are references to objects, not objects themselves, so when you call map.put("key", strings) it is a reference to the underlying HashSet that is passed; hence when you later update the HashSet the HashMap is updated too.

于 2012-10-10T13:57:59.417 回答