zoukankan      html  css  js  c++  java
  • HashMap 中 Key 类型的选择

    什么对象可以作为HashMap的key值?

    从HashMap的语法上来讲,一切对象都可以作为Key值。如:Integer、Long、String、Object等。但是在实际工作中,最常用的使用String作为Key值。

    原因如下:

    1.使用Object作为Key值的时候,如Class Person (里面包含,姓名,年龄,性别,电话等属性)作为Key。当Person类中的属性改变时,导致hashCode的值也发生变化,变化后,map.get(key)因为hashCode值的变化,而无法找到之前保存的value值,同样,删除也取不到值。

    解决方案是重写HashCode方法

    2.避免使用Long,Integer做key。有一次项目里排查bug,最后发现这个坑,由于拆箱装箱问题,导致取不到数据。

     1     Map<Integer, String> map1 = new HashMap<Integer, String>();
     2     map1.put(11, "11");
     3     map1.put(22, "22");
     4     long key1 = 11;
     5     System.out.println(map1.get(key1));  // null
     6         
     7     Map<Long, String> map2 = new HashMap<Long, String>();
     8     map2.put(11L, "11");
     9     map2.put(22L, "22");
    10     int key2 = 11;
    11     System.out.println(map1.get(key2));  // 11

    关于拆箱装箱,大家可以运行下面代码,尝试一下。类似下面代码的操作应该极力避免。

     1         Integer a = 1;
     2         Integer b = 2;
     3         Integer c = 3;
     4         Integer d = 3;
     5         Integer e = 321;
     6         Integer f = 321;
     7         Long g = 3L;
     8         System.out.println(c == d);
     9         System.out.println(e == f);
    10         System.out.println(c == (a+b));
    11         System.out.println(c.equals(a+b));
    12         System.out.println(g == (a+b));
    13         System.out.println(g.equals(a+b));            

    所以,综上所述,最好使用String来作为key使用。

  • 相关阅读:
    工作总结 vue 城会玩
    vue中,class、内联style绑定、computed属性
    vue-router2.0 组件之间传参及获取动态参数
    vue-router(2.0)
    在v-for中利用index来对第一项添加class(vue2.0)
    机器学习:从入门到沉迷
    探索AutoLayout的本质和解决一些问题
    软件的极简主义
    数组最大差值的最优解法(动态规划)
    项目管理--敏捷开发在项目中使用
  • 原文地址:https://www.cnblogs.com/lihao007/p/12444193.html
Copyright © 2011-2022 走看看