温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java项目中什么情况下HashCode会出现重复

发布时间:2020-11-27 17:11:54 来源:亿速云 阅读:368 作者:Leah 栏目:编程语言

java项目中什么情况下HashCode会出现重复?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

java的缺省算法:  

public int hashCode() { 
  int h = hash; 
  if (h == 0) { 
    int off = offset; 
    char val[] = value; 
    int len = count; 
 
      for (int i = 0; i < len; i++) { 
        h = 31*h + val[off++]; 
      } 
      hash = h; 
    } 
    return h; 
  }

但是什么情况下会重复?下面是测试代码

import java.util.HashMap; 
 
public class Test { 
 
  static HashMap map = new HashMap(); 
 
  private static char startChar = 'A'; 
 
  private static char endChar = 'z'; 
 
  private static int offset = endChar - startChar + 1; 
 
  private static int dup = 0; 
 
  public static void main(String[] args) { 
    int len = 3; 
    char[] chars = new char[len]; 
    tryBit(chars, len); 
    System.out.println((int)Math.pow(offset, len) + ":" + dup); 
  } 
 
  private static void tryBit(char[] chars, int i) { 
    for (char j = startChar; j <= endChar; j++) { 
      chars[i - 1] = j; 
      if (i > 1) 
        tryBit(chars, i - 1); 
      else 
        test(chars); 
    } 
  } 
 
  private static void test(char[] chars) { 
 
    String str = new String(chars).replaceAll("[^a-zA-Z_]", "").toUpperCase();// 195112:0 
    //String str = new String(chars).toLowerCase();//195112:6612 
    //String str = new String(chars).replaceAll("[^a-zA-Z_]","");//195112:122500 
    //String str = new String(chars);//195112:138510 
    int hash = str.hashCode(); 
    if (map.containsKey(hash)) { 
      String s = (String) map.get(hash); 
      if (!s.equals(str)) { 
        dup++; 
        System.out.println(s + ":" + str); 
      } 
    } else { 
      map.put(hash, str); 
      // System.out.println(str); 
    } 
  } 
}

在A-z范围内有特殊字符,从结果看,仅仅3位长度的字符串:

不处理: 138510次重复

去掉字母意外字符: 122500次重复

所有字符转小写:6612次重复(少了很多)

去掉字母意外字符,并且转小写:没有重复!4位字符串也没见重复

不难看出:

1. 缺省实现为英文字母优化
2. 字母大小写可能导致重复

可能:

长字符串可能hashcode重复
中文字符串和特殊字符可能hashcode重复

关于java项目中什么情况下HashCode会出现重复问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注亿速云行业资讯频道了解更多相关知识。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI