麻烦解释一下
String a = new String("了解");
String b = new String("了解");
这两个不同的对象用equals比较内容是一样的,但是hashcode为什么也相同??

解决方案 »

  1.   

    这是hashCode()的源代码,一看便知
        /** The value is used for character storage. */
        private final char value[];    /** The offset is the first index of the storage that is used. */
        private final int offset;    /** The count is the number of characters in the String. */
        private final int count;    /** Cache the hash code for the string */
        private int hash; // Default to 0
        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;
        }
      

  2.   

    自己写类的时候最好当equals 时 hashcode也相等这是好的习惯
      

  3.   

    最好当equals 时 hashcode也相等
    -------
    不是“最好”而是“必须”!
      

  4.   

    http://blog.csdn.net/fishyqd/archive/2006/08/17/1086641.aspx
      

  5.   

    Hashcode的作用就是用来标示元素在hash表中的位置,这是它存在的意义。所以,两个equals相等的元素,即认为是两个相同的元素,当然是存在于hash表中的同一个位置,既然是同一个位置hashcode就相等了。
      

  6.   

    a和b其实不是对象,而是指向对象的引用,相当于c++中的指针。
      

  7.   

    if a.equals(b)==true 那么hashcode也相同,如果hashcode相同,未必 equals成立
      

  8.   

    if a.equals(b)==true 那么hashcode也相同,如果hashcode相同,未必 equals成立这个是理论上应该这样,实际操作时,只要程序员重写EQUALS方法的时候没有重写HASHCODE,那就可能发生EQUALS方法为TRUE,hashcode不相同的情况。不是说这样不可以,也可以,但是HASHCODE已经失去了作用。
      

  9.   

    好像相同的二进制文件,如new FileInputStream(c:\test.txt),得到的hashcode怎么每次都不相同呢?文件没被改过
      

  10.   

    hashcode是对象在key-value映射集合当中hash函数生成的hash码,可以通过hashcode反算出对象地址,非常适合快速查找。JAVA对象的hashcode是通过对象的地址算出来的整数,不会重复,hashcode方法就是返加这个hashcode的方法,所以楼上的民工虽然实例化文件名相同的流对象,但每个对象的地址不同,他们的hashcode当然不同。而equals只是比较对象内容是否相等,比如比较对象中所有的属性是否相等。