java 中HashCode重復的可能性
java 中HashCode重復的可能性
今天有同事提議用String的hashcode得到int類型作為主鍵。其實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范圍內(nèi)有特殊字符,從結(jié)果看,僅僅3位長度的字符串:
不處理: 138510次重復
去掉字母意外字符: 122500次重復
所有字符轉(zhuǎn)小寫:6612次重復(少了很多)
去掉字母意外字符,并且轉(zhuǎn)小寫:沒有重復!4位字符串也沒見重復
不難看出:
1. 缺省實現(xiàn)為英文字母優(yōu)化
2. 字母大小寫可能導致重復
可能:
長字符串可能hashcode重復
中文字符串和特殊字符可能hashcode重復
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持,如有疑問請留言或者到本站社區(qū)交流討論,大家共同進步!
相關(guān)文章
SpringCloud Alibaba使用Seata處理分布式事務(wù)的技巧
在傳統(tǒng)的單體項目中,我們使用@Transactional注解就能實現(xiàn)基本的ACID事務(wù)了,隨著微服務(wù)架構(gòu)的引入,需要對數(shù)據(jù)庫進行分庫分表,每個服務(wù)擁有自己的數(shù)據(jù)庫,這樣傳統(tǒng)的事務(wù)就不起作用了,那么我們?nèi)绾伪WC多個服務(wù)中數(shù)據(jù)的一致性呢?跟隨小編一起通過本文了解下吧2021-06-06SpringBoot接口限流的實現(xiàn)方法小結(jié)
在一個高并發(fā)系統(tǒng)中對流量的把控是非常重要的,當巨大的流量直接請求到我們的服務(wù)器上沒多久就可能造成接口不可用,不處理的話甚至會造成整個應(yīng)用不可用,所以我們需要接口限流,本文給大家介紹了SpringBoot接口限流的實現(xiàn)方法,需要的朋友可以參考下2024-10-10SpringBoot 如何使用Dataway配置數(shù)據(jù)查詢接口
這篇文章主要介紹了SpringBoot 如何使用Dataway配置數(shù)據(jù)查詢接口,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-11-11