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

  

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

java的缺省算法:,,

public  int  HashCode (), {,   int 才能;h =,散列,,   if 才能;(h ==, 0), {,   ,,,int  off =,抵消,,   ,,,char  val[],=,价值,,   ,,,int  len =,计数,,   ,   ,,,,,for  (int 小姐:=,0;,小姐:& lt;, len;,我+ +),{,   ,,,,,,,h =, 31 * h  +,瓦尔(+ +),,   ,,,,,},   ,,,,,hash =, h,,   ,,,},   ,,,return  h,,   以前,,}

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

import  java.util.HashMap;,   ,   {public  class  Test    ,   static 才能HashMap  map =, new  HashMap (),,   ,   private 才能static  char  startChar =, & # 39;一个# 39;,,   ,   private 才能static  char  endChar =, & # 39; z # 39;,,   ,   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(字符,len);,   ,,,System.out.println ((int) Math.pow(抵消,len), +,“:“, +, dup),,   ,,},   ,   private 才能static  void  tryBit (char[],是,,int  i), {,   ,,,for  (char  j =, startChar;, j  & lt;=, endChar;, j + +), {,   ,,,,,字符[小姐,安康;1],=,j。,   ,,,,,if (,小姐的在,1),   ,,,,,,,tryBit(识字课,,小姐:安康;1),,   ,,,,,else    ,,,,,,,测试(字符),,   ,,,},   ,,},   ,   private 才能;static  void 测试(char[],识字课),{,   ,   ,,,String  str =, new 字符串(字符).replaceAll (“[^ a-zA-Z_]“,,,,) .toUpperCase ();//, 195112:0    ,,,//String  str =, new 字符串(字符).toLowerCase ();//195112:6612    ,,,//String  str =, new 字符串(字符).replaceAll (“[^ a-zA-Z_]“,““);//195112:122500    ,,,//String  str =, new 字符串(字符);//195112:138510    ,,,int  hash =, str.hashCode (),,   ,,,if  (map.containsKey (hash)), {,   ,,,,,String  s =,(字符串),map.get (hash);,   ,,,,,if  (! s.equals (str)), {,   ,,,,,,,,dup + +;   ,,,,,,,System.out.println (s  +,“:“, +, str),,   ,,,,,},   ,,,},else  {,   ,,,,,map.put(散列,str);,   ,,,,,//,System.out.println (str);,   ,,,},   ,,},   }

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

不处理:138510次重复

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

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

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

<强>不难看出:

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

<强>可能:

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

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

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