zoukankan      html  css  js  c++  java
  • Java自定义类型作为HasMap的key的查找

    最近常常会用到一些之前看过却没有实际去实现的小细节,深有感慨(掌握一门技术绝不是看一遍就够了,一遍远远不够,远远不够........),

    言归正传,先直接上代码

    Attributeresult

     1 public class Attributeresult {
     2     String value;
     3     String result;
     4 
     5     public Attributeresult() {
     6 
     7     }
     8 
     9     public Attributeresult(String value, String result) {
    10         this.value = value;
    11         this.result = result;
    12     }
    13 
    14     @Override
    15     public boolean equals(Object o) {
    16         if (this == o)
    17             return true;
    18         if (o == null || getClass() != o.getClass())
    19             return false;
    20         Attributeresult attributeresult = (Attributeresult) o;
    21         if (attributeresult.result == null || attributeresult.value == null)
    22             return false;
    23         if (value.equals(attributeresult.value) && result.equals(attributeresult.result))
    24             return true;
    25         return false;
    26     }
    27 
    28     @Override
    29     public int hashCode() {
    30         return value != null ? value.hashCode() : 0;
    31     }
    32     public static void main(String[] args) {
    33         Map<Attributeresult, Integer> valuelist = new HashMap<Attributeresult, Integer>();
    34         valuelist.put(new Attributeresult("mim", "yes"), 20);
    35         valuelist.put(new Attributeresult("mim", "no"), 1);
    36         valuelist.put(new Attributeresult("xunying", "yes"), 60);
    37         valuelist.put(new Attributeresult("xunying", "no"), 2);
    38         valuelist.put(new Attributeresult("mini", "no"), 2);
    39         if(valuelist.containsKey(new Attributeresult("xunying","yes"))){
    40             System.out.println("存在");
    41         }else{
    42             valuelist.put(new Attributeresult("mini","yes"),30);
    43         }
    44     }
    45 
    46 }

    运行结果肯定是:存在

    这里面Attributeresult类重载了hasCode()方法和equals()方法,所以才能查找存在,如果不重写,containsKey()返回的必然是false,因为默认情况下是:

    HashMap中,查找key的比较顺序为:

    1. 计算对象的Hash Code,看在表中是否存在。
    2. 检查对应Hash Code位置中的对象和当前对象是否相等

    第一步就是要用到hashCode()方法,而第二步就是要用到equals()方法。

    在没有进行重载时,在这两步会默认调用Object类的这两个方法,而在Object中,Hash Code的计算方法是根据对象的地址进行计算的。

    • 重载hashCode()是为了对同一个key,能得到相同的Hash Code,这样HashMap就可以定位到我们指定的key上。
    • 重载equals()是为了向HashMap表明当前对象和key上所保存的对象是相等的,这样我们才真正地获得了这个key所对应的这个键值对。

    上面的总结是源于https://segmentfault.com/a/1190000002655085,感谢

  • 相关阅读:
    从淘宝数据结构来看电子商务中商品属性设计
    YY淘宝商品数据库设计
    ElasticSearch-聚合bucket学习
    ElasticSearch-聚合bucket
    Elasticsearch(9) --- 聚合查询(Bucket聚合)
    Elasticsearch-多字段搜索(Multifield Search)和提高精确度
    五、设备管理与文件系统
    六、YUM仓库
    四、查找命令
    二、用户权限
  • 原文地址:https://www.cnblogs.com/xunyingFree/p/5358260.html
Copyright © 2011-2022 走看看