• HashMap支持key是null,value也为null,在从Map中取出key对应的value后,要做一个空判断,防止出现空指针;
    • ConcurrentHashMap不支持key和value为null,containsKey也不支持传空,所以ConcurrentHashMap在put值进去和判断是否有值的时候一定要做空判断。在工作中如果使用ConcurrentHashMap时,建议使用抽出几个工具方法,省得判空方法散落在各处;

      1. /**
      2. * @param concurrentHashMap ConcurrentHashMap
      3. * @param key String
      4. * @param value String
      5. */
      6. public static void putValue(ConcurrentHashMap<String, Object> concurrentHashMap, String key, String value) {
      7. if (concurrentHashMap == null || key == null || value == null) {
      8. return;
      9. }
      10. concurrentHashMap.put(key, value);
      11. }
      12. /**
      13. * @param concurrentHashMap ConcurrentHashMap
      14. * @param key String
      15. * @return boolean
      16. */
      17. public static boolean containsKey(ConcurrentHashMap<String, Object> concurrentHashMap, String key) {
      18. if (key == null || concurrentHashMap == null) {
      19. return false;
      20. }
      21. return concurrentHashMap.containsKey(key);
      22. }