2012-05-23 4 views
0

2 개의 머시닝해야하는 프로그램이 있습니다 HashMap. 해시 맵의 키는 String이고 값은 Integer입니다. 병합의 특수한 조건은 키가 사전에 이미있는 경우 Integer을 기존 값에 추가하고이를 대체하지 않아야한다는 것입니다. 지금까지 내가 가지고있는 코드는 NullPointerException입니다.Java에서 2 HashMaps 병합

public void addDictionary(HashMap<String, Integer> incomingDictionary) { 
     for (String key : incomingDictionary.keySet()) { 
      if (totalDictionary.containsKey(key)) { 
       Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key); 
       totalDictionary.put(key, newValue); 
      } else { 
       totalDictionary.put(key, incomingDictionary.get(key)); 
      } 
     } 
    } 
+0

NPE는 어떤 라인에 던져 집니까? – BenCole

+0

'totalDictionary' 필드를 초기화 했습니까? – BenCole

+0

totalDictionary는이 함수를 래핑하는 클래스의 이전에 private 멤버 데이터로 선언되었지만 초기화되지 않았습니다. Eclipse는 for 루프가있는 행에서 예외가 발생 함을 보여줍니다. – SmashCode

답변

1

것은, 당신이

public void addDictionary(HashMap<String, Integer> incomingDictionary) { 
    if (incomingDictionary == null) { 
     return; // or throw runtime exception 
    } 
    if (totalDictionary == null) { 
     return;// or throw runtime exception 
    } 
    if (totalDictionary.isEmpty()) { 
     totalDictionary.putAll(incomingDictionary); 
    } else { 
     for (Entry<String, Integer> incomingIter : incomingDictionary.entrySet()) { 
      String incomingKey = incomingIter.getKey(); 
      Integer incomingValue = incomingIter.getValue(); 
      Integer totalValue = totalDictionary.get(incomingKey); 
      // If total dictionary contains null for the incoming key it is 
      // as good as replacing it with incoming value. 
      Integer sum = (totalValue == null ? 
              incomingValue : incomingValue == null ? 
                totalValue : totalValue + incomingValue 
         ); 
      totalDictionary.put(incomingKey, sum); 
     } 
    } 
} 
결코 밖으로 널 체크를해야 할 것 :
은 어쩌면 당신은 전에이 같은 것을 추가해야 의 HashMap을 고려

이 두 가지 중 하나가 N 인 경우 NPE하는 경향이 코드에서 다른 장소

Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key); 

인 값으로 널 (null) 허용 너는 NPE를 얻을 것이다.

+0

if (totalDictionary.isEmpty()) then totalDictionary.putAll (incomingDictionary) else for for 루프를 수행할까요? – SmashCode

+0

incomingDictionary가 null의 경우, putAll가 NullPointerException를 슬로우합니다. – mprabhat

+0

@SmashCode가 대답을 업데이트했습니다. – mprabhat

0

totalDictionary가 올바르게 초기화하는 것을 고려 :

Integer newValue = incomingDictionary.get(key) + totalDictionary.get(key); 

totalDictionary.get(key)null를 반환 할 수 없었다. 코드가 incomingDictionary는이 방법을 도달하기 전에 초기화 할 것이라는 점을 보장 할 수없는 경우

if(totalDictionary.get(key) == null) 
    totalDictionary.put(key, 0); 
2

아마도 사전 중 하나가 초기화되지 않았습니다. 다음은 하나의 솔루션입니다.

public void addDictionary(HashMap<String, Integer> incomingDictionary) { 
    if (incomingDictionary == null) { 
     throw new IllegalArgumentException("incomingDictionary cannot be null."); 
    } 
    if (totalDictionary == null) { 
     throw new IllegalArgumentException("totalDictionary cannot be null."); 
     // or another solution: 
     // totalDictionary = new HashMap<String, Integer>(); 
     // totalDictionary.putAll(incomingDictionary); 
     // return; 
    } 

    for (Map.Entry<String, Integer> entry : incomingDictionary.entrySet()) { 
     Integer oldValue = totalDictionary.get(entry.getKey()); 
     if (oldValue != null){ 
      // here entry.getValue() could be null! 
      // Never put a null value in your Map, or add a test here 
      Integer newValue = entry.getValue() + oldValue; 
      totalDictionary.put(entry.getKey(), newValue); 
     } else { 
      totalDictionary.put(entry.getKey(), entry.getValue()); 
     } 
    } 
} 
+0

+1 조용히 실패하지 않고 예외를 throw합니다. – BenCole

+1

entry.getValue()가 null을 반환하면 NPE – mprabhat

+0

실제로! 그러나 나는지도에서 값으로 'null'을 절대 쓰지 않는 것이 그의 책임이라고 생각합니다. 그러나 귀하의 의견에 따라 내 게시물을 편집 할 것입니다. –