zoukankan      html  css  js  c++  java
  • hashcode与字符串

    http://blog.csdn.net/zwy9002/article/details/7592719

    问题1. 不同的字符串可能会有相同的HashCode吗?

    答案: 可能。hashcode是用来判断两个字符串是否相等的依据,不同的字符串不可能有相同的hashcode,但不同的hashCode经过与长度的取余,就很可能产生相同的hashCode,就是所谓的哈希冲突. 如:

    	public static void main(String[] args) {
    
    		int hash1 = "ABCDEa123abc".hashCode();
    		int hash2 = "ABCDFB123abc".hashCode();
    		System.out.println(hash1);
    		System.out.println(hash2);
    	}
    
    output:
    165374702
    165374702 
    

    延伸问题: hashcode相同,字符串相同吗?答案是不一定。

    问题2. 相同的字符串可能会有不同的HashCode吗

    答案: 不可能。

    如果你自己重写equals和hashcode方法是可以实现的,但是java规范要求两个equals的对象一定要有相同的hashcode。
    String类是jdk里的基础类,是严格遵守规范的,而且是final的,不能继承,所以也没有重写覆盖hashcode方法的可能。
    问题3. 相同的字符串每次生成的HashCode都相同吗?
    答案: 一定相同。
    hashcode是由简单的Hash算法得出来的,根据字符串的值算出来的,每次算出来的结果都相同 
  • 相关阅读:
    数据仓库与数据挖掘的一些基本概念
    System.currentTimeMillis();
    html练习(3)
    HDU 1556 Color the ball【算法的优化】
    ubuntu12.04 安装配置jdk1.7
    java中的switch用String作为条件
    oracle中 connect by prior 递归算法
    C#复习题
    AngularJS:Http
    AngularJS:Service
  • 原文地址:https://www.cnblogs.com/sunxucool/p/3393800.html
Copyright © 2011-2022 走看看