A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 黑马11期李项京 中级黑马   /  2012-5-25 13:33  /  4762 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

我的理解是通过常量名和方法名来计算hash code,是这样吗?

5 个回复

倒序浏览
hashcode()方法可以覆写的,也就是说每个对象都未必一样。
下面是string的hashcode方法
  1.    public int hashCode() {
  2.         int h = hash;
  3.         if (h == 0 && count > 0) {
  4.             int off = offset;
  5.             char val[] = value;
  6.             int len = count;

  7.             for (int i = 0; i < len; i++) {
  8.                 h = 31*h + val[off++];
  9.             }
  10.             hash = h;
  11.         }
  12.         return h;
  13.     }
复制代码
回复 使用道具 举报
张晨 发表于 2012-5-25 14:22
hashcode()方法可以覆写的,也就是说每个对象都未必一样。
下面是string的hashcode方法 ...

答非所问,不改写的时候,虚拟机是怎么计算的?:#
回复 使用道具 举报
    public native int hashCode();
这个是在java.lang.Objetc.java文件中找出来的hashCode的代码
不知道是不是楼主你要的答案?
回复 使用道具 举报
本帖最后由 小小企鹅 于 2012-10-27 22:35 编辑

Object的hashCode()是一个本地方法,调用的是底层的hash值,可以用来比较内存地址,因为不是一个java编写的方法,查看源码找不到它的实现。
可以复写hashCode方法,比如String类中:
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;
    }
回复 使用道具 举报
兄弟们,最后还是被我发现虚拟机的中的计算公式{:soso_e182:}int java.lang.String.hashCode()

hashCode
public int hashCode()
Returns a hash code for this string. The hash code for a String object is computed as
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]//计算公式

using int arithmetic(算法), where s[i] is the ith character of the string, n is the length of the string, and ^ indicates(表示) exponentiation(取幂). (The hash value of the empty string is zero.)

Overrides:
hashCode in class Object
Returns:
a hash code value for this object.
See Also:
Object.equals(java.lang.Object), Hashtable
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马