2012-10-10 4 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

align 속성이 Table과 일치하는 HashSet의 일부가되기를 원하지 않습니다. – Sriharsha

답변

1

코드는 예상대로 작동해야합니다. 동작을 보여줍니다 다음 (간체) 예를 고려해 자바 변수는 오브젝트 자체되지 객체에 대한 참조입니다, 그래서 당신은 map.put("key", strings)를 호출 할 때 전달되는 기본 HashSet에 대한 참조입니다

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

} 

참고; 따라서 나중에 HashSet을 업데이트하면 HashMap도 업데이트됩니다.

관련 문제