zoukankan      html  css  js  c++  java
  • Hashed collections哈希集合

      【定义】

    有index的集合

     

    【hash的原理】

    term for a situation when two different objects return the same hashcode: hash collision

    就是无规律的一一对应排序,相同object对应的HASH应该相同,相同对应的HASH应该不同。具体实现:hashCode(It returns an int hash-code depending on the memory address of the object 根据obeject的位置来对应in the heap) equal() 都是自动继承的。

    Use a function on hashcode, such as modulo, to calculate the index into the hashtable and then store the object at that index 根据hash的index来查找物体

     

    【实现】

    object有三种方法toString equal hashcode,通过传入memory address来计算值。同一obeject的不同state状态:要避免collision。

     

    public int hashCode() {  
    return  Objects.hash(title, author, year);   //hash on instance variable values
    }
    //equals() implements equivalence relation - reflexive, symmetric, transitive, consistent – 
    // on non-null object references
    @Override
    public boolean equals(Object o) { 
    if (o == null) return false;  // if o is null, then it can’t be equal to ‘this’ 
    if (this == o) return true;   // if both point to same object, then they are equal
    if (getClass() != o.getClass()) return false; //if not of same type, they can’t be equal
    Book b = (Book) o; //now that we know o is unique, non-null Book object, cast it to Book
    return title.equals(b.title) && author.equals(b.author) && (year == b.year); //compare values
    }

    【步骤】

    先用hashcode,再用equals。因为state不同要overload, 只overload一个会发生inconsistent。

     

    【区别】

    object/key来hash

     

    【treemap】

    排序的map,里面是BST

    【map的三个集合】

    entryset keyset values 

    remove(k) 是remove key = k的entry

  • 相关阅读:
    进阶系列(8)——匿名方法与lambda表达式
    进阶系列(3)—— 序列化与反序列化
    进阶系列(4)——扩展方法
    数据库设计开发规范
    .Net 项目代码风格
    用JS获取地址栏参数的方法(超级简单)
    Ajax轮询 select循环输出
    【Jquery】jquery刷新页面(局部及全页面刷新)
    网页上 滚动代码 最简单的
    eazyui 或bootstrap table表格里插入图片,点击查看大图
  • 原文地址:https://www.cnblogs.com/immiao0319/p/9841048.html
Copyright © 2011-2022 走看看