ΪʲôhashcodeҪʹÓÃ31Õâ¸öÊý_JAVA_±à³Ì¿ª·¢_³ÌÐòÔ±¾ãÀÖ²¿

ÖйúÓÅÐãµÄ³ÌÐòÔ±ÍøÕ¾³ÌÐòԱƵµÀCXYCLUB¼¼ÊõµØͼ
ÈÈËÑ£º
¸ü¶à>>
 
ÄúËùÔÚµÄλÖ㺠³ÌÐòÔ±¾ãÀÖ²¿ > ±à³Ì¿ª·¢ > JAVA > ΪʲôhashcodeҪʹÓÃ31Õâ¸öÊý

ΪʲôhashcodeҪʹÓÃ31Õâ¸öÊý

 2014/5/21 19:09:47  wfh6732  ³ÌÐòÔ±¾ãÀÖ²¿  ÎÒÒªÆÀÂÛ(0)
  • ÕªÒª£ºÉ¢ÁмÆËã¾ÍÊǼÆËãÔªËØÓ¦¸Ã·ÅÔÚÊý×éµÄÄĸöÔªËØÀ׼ȷµÄ˵ÊǷŵ½ÄĸöÁ´±íÀïÃæ¡£°´ÕÕJavaµÄ¹æÔò£¬Èç¹ûÄãÒªÏ뽫һ¸ö¶ÔÏó·ÅÈëHashMapÖУ¬ÄãµÄ¶ÔÏóµÄÀà±ØÐëÌṩhashcode·½·¨£¬·µ»ØÒ»¸öÕûÊýÖµ¡£±ÈÈçStringÀà¾ÍÓÐÈçÏ·½·¨£ºpublicinthashCode(){inth=hash;intlen=count;if(h==0&&len>0){intoff=offset;charval[]=value;for(inti=0;i<len;i++)
  • ±êÇ©£ºhas ʹÓà Hash ʲô Ϊ Ϊʲô
É¢ÁмÆËã¾ÍÊǼÆËãÔªËØÓ¦¸Ã·ÅÔÚÊý×éµÄÄĸöÔªËØÀ׼ȷµÄ˵ÊǷŵ½ÄĸöÁ´±íÀïÃæ¡£°´ÕÕJavaµÄ¹æÔò£¬Èç¹ûÄãÒªÏ뽫һ¸ö¶ÔÏó·ÅÈëHashMapÖУ¬ÄãµÄ¶ÔÏóµÄÀà±ØÐëÌṩhashcode·½·¨£¬·µ»ØÒ»¸öÕûÊýÖµ¡£±ÈÈçStringÀà¾ÍÓÐÈçÏ·½·¨£º
class="java" name="code">public int hashCode() {  
        int h = hash;  
        int len = count;  
        if (h == 0 && len > 0) {  
            int off = offset;  
            char val[] = value;  
  
            for (int i = 0; i < len; i++) {  
                h = 31*h + val[off++];  
            }  
            hash = h;  
        }  
        return h;  
    }  


×¢ÒâÉÏÃæµÄforÑ­»·£¬Óеã¸ã°É£¿ÎÒÀ´¾Ù¸öÀý×Ó£¬ÈÃÄãºÜÈÝÒ×Ã÷°×ËüÔÚ¸ãʲôÃûÌᣱÈÈçÓÐÒ»¸ö×Ö·û´®¡°abcde¡±,²ÉÓÃ31½øÖƵļÆËã·½·¨À´¼ÆËãÕâ¸ö×Ö·û´®µÄ×ܺͣ¬Äã»áд³öÏÂÃæµÄ¼ÆËãʽ×Ó£º
a*31^4+b*31^3+c*31^2+d*31^1+e*31^0.×¢Ò⣬ÕâÀïµÄa,b,c,d»òÕßeÖ¸µÄÊÇËüÃǵÄASCIIÖµ¡£ºÜÓÐȤµÄÑ­»·£¬¾ÓÈ»¿ÉÒÔÓÃÀ´ËãN½øÖÆ¡£Õâ¸öÑ­»·¿ÉÒÔ³é³öÀ´µ¥¶À×÷Ϊ¼ÆËã½øÖƵĺù¤¾ß£º
public static void main(String[] args) {  
        int[] a={1,0};  
        System.out.println(calculate(2,a));  
    }  
  
    private static int calculate(int radix,int[] a){  
        int sum = 0;  
        for(int i=0;i<a.length;++i){  
            sum = sum*radix+a[i];  
        }  
        return sum;  
    }  

¾²Ì¬·½·¨caculate½ÓÊÜradix×÷Ϊ½øÖÆ»ùÊý£¬Êý×éaÄ£ÄâÒª¼ÆËãµÄ½øÖƵÄÊý×Ö£¬Ö»ÊÇ×¢Òâ±íÃæ˳ÐòÐèÒªÒ»Ö¡£±ÈÈç 01 ¶þ½øÖÆ´®£¬ÔÚÊý×éÖÐÒª°´ÕÕ{0,1}ÅÅÁС£ÉÏÃæµÄÊä³ö½á¹ûÊÇ1£¬·ûºÏ01µÄÕæʵֵ¡£
  ÄÇôΪʲôѡÓÃ31×÷Ϊ»ùÊýÄØ£¿ÏÈÒªÃ÷°×ΪʲôÐèÒªHashCode.ÿ¸ö¶ÔÏó¸ù¾ÝÖµ¼ÆËãHashCode,Õâ¸öcode´óСËäÈ»²»ÉÝÇó±ØÐëΨһ£¨ÒòΪÕâÑùͨ³£¼ÆËã»á·Ç³£Âý£©£¬µ«ÊÇÒª¾¡¿ÉÄܵIJ»ÒªÖظ´£¬Òò´Ë»ùÊýÒª¾¡Á¿µÄ´ó¡£ÁíÍ⣬31*N¿ÉÒÔ±»±àÒëÆ÷ÓÅ»¯Îª
×óÒÆ5λºó¼õ1£¬ÓнϸߵÄÐÔÄÜ¡£ÆäʵѡÓÃ31»¹ÊÇÓÐÕùÒ飬·´¶ÔÕߣ¨²Î¿¼http://stackoverflow.com/questions/299304/why-does-javas-hashcode-in-string-use-31-as-a-multiplier£©
ÈÏΪÕâ¸ö¶«Î÷»¹ÊǻᵼÖ½϶àµÄÖظ´£¬Ó¦¸ÃÓøü´óµÄÊý×Ö¡£ËùÒÔ£¬»òÐí½«À´JavaµÄʵÏÖÖлáÓÐËù±ä»¯¡£ÏÂÃæÕâƪÎÄÕ½éÉÜÁËÁ½¸ö½áÂÛ£º
1.»ùÊýÒªÓÃÖÊÊý
ÖÊÊýµÄÌØÐÔ£¨Ö»ÓÐ1ºÍ×Ô¼ºÊÇÒò×Ó£©Äܹ»Ê¹µÃËüºÍÆäËûÊýÏà³ËºóµÃµ½µÄ½á¹û±ÈÆäËû·½Ê½¸üÈÝÒײú³ÉΨһÐÔ£¬Ò²¾ÍÊÇhash codeÖµµÄ³åÍ»¸ÅÂÊ×îС¡£
2.Ñ¡Ôñ31Êǹ۲â·Ö²¼½á¹ûºóµÄÒ»¸öÑ¡Ôñ£¬²»Çå³þÔ­Òò£¬µ«µÄÈ·ÓÐÀû¡£
http://computinglife.wordpress.com/2008/11/20/why-do-hash-functions-use-prime-numbers/
ÁíÍ⣬String.hashCodeÄÚ²¿»á»º´æµÚÒ»´Î¼ÆËãµÄÖµ£¬ÒòΪÕâÊÇÒ»¸öfinal£¨²»¿É±ä£©À࣬Ҳ¾ÍÊÇString¶ÔÏóµÄÄÚÈÝÊDz»»á±äµÄ¡£ÕâÄܹ»ÔÚ¶à´Îputµ½HashMapµÄ³¡ºÏÌá¸ßÐÔÄÜ£¬²»¹ýËƺõÓô¦²»¶à¡£
·¢±íÆÀÂÛ
Óû§Ãû: ÄäÃû