1

我有一个哈希图,例如,

public static void main(String[] args) {
    final Map<String, String> daysMap = new HashMap(7);
    daysMap.put("1", "Sunday");
    daysMap.put("2", "Monday");
    daysMap.put("3", "Tuesday");
    daysMap.put("4", "Wednesday");
    daysMap.put("5", "Thursday");
    daysMap.put("6", "Friday");
    daysMap.put("7", "Saturday");
}

在此地图
中 1. 不应允许放置超过 7 个元素
2. 不应更新相应键的值 [like daysMap.put("5", "xxx");]
3. 不应允许删除任何键

怎么做?

4

4 回答 4

7

您可以实现一个新的 HashMap

public class CoolMap<K, V> extends HashMap<K, V> {

@Override
public V put(K key, V value) {

    if (size() == 7) {
        throw new IllegalStateException("Size is at max!");
    } else {

        // If there is something already with that key
        if (containsKey(value)) {
            // do nothing
            return value;
        } else {
            // put inside
            return super.put(key, value);
        }

    }

}

@Override
public void putAll(Map<? extends K, ? extends V> collection) {

    if (collection.size() > 7) {
        throw new IllegalStateException("Size is at max!");
    } else {
        super.putAll(collection);
    }

}

@Override
public V remove(Object key) {
    return null;// doesn't remove anything
}
于 2013-07-30T11:19:35.777 回答
5

第 2 点和第 3 点由 覆盖Collections.unmodifiableMap。为了涵盖第一点,您可以添加手写测试。

于 2013-07-30T11:09:50.417 回答
1

正如已经讨论过的,第 2 点和第 3 点是这样覆盖的

import java.util.*;

    public class OP2 {
       public static void main(String[] s) {
          //object hash table 
          Hashtable<String,String> table = new Hashtable<String,String>();
          table.

          // populate the table
          table.put("1", "Sunday");
          table.put("2", "Monday");
          table.put("3", "Tuesday");
          table.put("4", "Wednesday");
          table.put("5", "Thursday");
          table.put("6", "Friday");
          table.put("7", "Saturday");

          System.out.println("Initial collection: "+table);

          // create unmodifiable map
          Map m = Collections.unmodifiableMap(table);

          // try to modify the collection
         // m.put("key3", "value3");
         //Uncomment the above line and an error is obtained
       }
    }

此外,对于第一个问题,最好在填充地图时调用一个函数:-

 public boolean putAndTest(MyKey key, MyValue value) {
            if (map.size() >= MAX && !map.containsKey(key)) {
                 return false;
            } else {
                 map.put("Whatever you want");
                 return true;
            }
        }
于 2013-07-30T11:23:47.633 回答
0

为什么不创建自己的包含私有哈希映射的对象,然后您可以允许该私有哈希映射上的哪些方法被公开?

于 2013-07-30T11:20:48.200 回答