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

© 生活如此多娇 中级黑马   /  2016-12-6 23:05  /  841 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

对象的哈希值

哈希值是一个对象存储哈希表的依据
对象的哈希值,普通的十进制整数
父类Object,方法 public int hashCode() 计算结果int整数,默认是会发生变化
子类可以重写hashCode自己计算哈希值
String类,重写了hashCode方法,自己去算哈希值.
  /*
   *  对象的哈希值,普通的十进制整数
   *  父类Object,方法 public int hashCode() 计算结果int整数
   */
  public class HashDemo {
    public static void main(String[] args) {
      Person p = new Person();
      int i = p.hashCode();
      System.out.println(i);

      String s1 = new String("abc");
      String s2 = new String("abc");
      System.out.println(s1.hashCode());
      System.out.println(s2.hashCode());

      /*System.out.println("重地".hashCode());
      System.out.println("通话".hashCode());*/
    }
  }

  //String类重写hashCode()方法
  //字符串都会存储在底层的value数组中{'a','b','c'}
  public int hashCode() {
          int h = hash;//hash初值为0
          if (h == 0 && value.length > 0) {
              char val[] = value;

              for (int i = 0; i < value.length; i++) {
                  h = 31 * h + val[i];
              }
              hash = h;
          }
          return h;
      }

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马