【问题标题】:HashSet values are computed wronglyHashSet 值计算错误
【发布时间】:2012-10-10 09:53:20
【问题描述】:

我正在使用 HashSet,它具有用于所有元素的一些属性,然后将此 Hashset 添加到每个元素对应的 HashMap 中。此外,为特定元素添加了一些属性(例如 THEAD )。

但后来添加的属性 align 存在于 Table 和 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);

【问题讨论】:

  • 我不希望 align 属性成为与 Table 相对应的 HashSet 的一部分。

标签: java hashmap hashset


【解决方案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 也会更新。

【讨论】:

    猜你喜欢
    • 2020-11-12
    • 2012-07-09
    • 2018-08-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 1970-01-01
    相关资源
    最近更新 更多