How can I have a HashMap with unique keys in java?

前端 未结 6 663
长发绾君心
长发绾君心 2021-02-11 13:36

How can I have a HashMap with unique keys in Java? Or even does this make any sense to have unique keys in HashMap or the keys are unique by default? I am a newbie. thx

6条回答
  •  粉色の甜心
    2021-02-11 13:52

    Hash map key is unique. Add duplicate key, then it will be overwritten.

     HashMap hm = new HashMap();
     hm.put("1", new Integer(1));
     hm.put("2", new Integer(2));
     hm.put("3", new Integer(3));
     hm.put("4", new Integer(4));
     hm.put("1", new Integer(5));// value integer 1 is overwritten by 5
    

    By default Hashmap is not synchronized.

提交回复
热议问题