What is the use of adding a null key or value to a HashMap in Java?

前端 未结 7 1408
挽巷
挽巷 2020-12-12 16:19

HashMap allows one null key and any number of null values. What is the use of it?

相关标签:
7条回答
  • 2020-12-12 16:52

    Here's my only-somewhat-contrived example of a case where the null key can be useful:

    public class Timer {
        private static final Logger LOG = Logger.getLogger(Timer.class);
        private static final Map<String, Long> START_TIMES = new HashMap<String, Long>();
    
        public static synchronized void start() {
            long now = System.currentTimeMillis();
            if (START_TIMES.containsKey(null)) {
                LOG.warn("Anonymous timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(null).longValue()) +"ms"); 
            }
            START_TIMES.put(null, now);
        }
    
        public static synchronized long stop() {
            if (! START_TIMES.containsKey(null)) {
                return 0;
            }
    
            return printTimer("Anonymous", START_TIMES.remove(null), System.currentTimeMillis());
        }
    
        public static synchronized void start(String name) {
            long now = System.currentTimeMillis();
            if (START_TIMES.containsKey(name)) {
                LOG.warn(name + " timer was started twice without being stopped; previous timer has run for " + (now - START_TIMES.get(name).longValue()) +"ms"); 
            }
            START_TIMES.put(name, now);
        }
    
        public static synchronized long stop(String name) {
            if (! START_TIMES.containsKey(name)) {
                return 0;
            }
    
            return printTimer(name, START_TIMES.remove(name), System.currentTimeMillis());
        }
    
        private static long printTimer(String name, long start, long end) {
            LOG.info(name + " timer ran for " + (end - start) + "ms");
            return end - start;
        }
    }
    
    0 讨论(0)
提交回复
热议问题