2011-01-10 2 views
2
import java.util.*; 
public class HashMapExample { 

    public static class WriteOnceMap<K, V> extends HashMap<K, V> { 

     public V put(K key, V value) { 
      /* 
      WriteOnceMap is a map that does not allow changing value for a particular key. 
      It means that put() method should throw IllegalArgumentException if the key is already 
      assosiated with some value in the map. 

      Please implement this method to conform to the above description of WriteOnceMap. 
      */ 
     } 


     public void putAll(Map<? extends K, ? extends V> m) { 
      /* 
      Pleaase implement this method to conform to the description of WriteOnceMap above. 
      It should either 
      (1) copy all of the mappings from the specified map to this map or 
      (2) throw IllegalArgumentException and leave this map intact 
      if the parameter already contains some keys from this map. 
      */ 
     } 
    } 
} 
+3

좋은 숙제, 무엇을 시도 했습니까? 당신의 대답은 – unbeli

답변

3
public static class WriteOnceMap<K, V> extends HashMap<K, V> { 
    public V put(K key, V value) { 
     if (containsKey(key)) 
      throw new IllegalArgumentException(key + " already in map"); 

     return super.put(key, value); 
    } 


    public void putAll(Map<? extends K, ? extends V> m) { 
     for (K key : m.keySet()) 
      if (containsKey(key)) 
       throw new IllegalArgumentException(key + " already in map"); 

     super.putAll(m); 
    } 
} 
+0

X보다 큽니다. 당신은 전문가입니다! 조언을 위해 – Mohsin

1

1 : 랩의 HashMap.

2 : 또는 사용이 숙제 경우 java.util.Collections.unmodifiableMap(Map<? extends K, ? extends V>)

dacwe는, 권리입니다.

+0

X보다. – Mohsin