有一个流传的变态级的JAVA程序员面试32问,我见过几次。
其中有一个问题是这样的:两个对象值相同(x.equals(y)==true),但却可有不同的hashcode,这句话对不对?
我以为这句话是对的;但是,看到几处给出的答案都是:不对,有相同的hashcode.难道我理解错了题目的意思。
我是这样想的:
自定义的一个类可以重载equals和hashCode方法,我可以在equals方法里任何情况都返回true,但hashCode里用当前时间的毫秒数作为返回值:这样,很明显的,对大多数的对象x.equals(y)==true但x.hashCode() != y.hashCode().当然,这样的重载是很有问题很不符合设计思想也没有什么实际用处的。但题目说的只是可能,难道不是么?

解决方案 »

  1.   

    给出其中的一个链接,有兴趣的可以看一下
    http://www.toidy.cn/gjbc/java/java49.html链接中此问题为29
      

  2.   

    Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode method, which states that equal objects must have equal hash codes. 
    -------------------------------------------------------------------------------
    这个是JDk 5.0的Object的equals方法说明的最后一句话,很明显重载这两个方法是有条件的,我当然可以随便重载,但是肯定不符合jdk规范,楼主相当于修改了jdk。这个题目本身也是没事找事
      

  3.   

    赫赫, 是可以做到的,但是不推荐这样做public class TestHashcode {

    private int hashcode = -1;
    private int flag = 0;

    public int hashCode() {
    return hashcode;
    } public boolean equals(Object obj) {
    if (obj instanceof TestHashcode && flag == ((TestHashcode)obj).flag) {
    return true;
    }
    return false;
    }

    public TestHashcode(int hashcode, int flag) {
    super();
    this.hashcode = hashcode;
    this.flag = flag;
    } public static void main(String[] args) {
    TestHashcode t1 = new TestHashcode (1, 1);
    TestHashcode t2 = new TestHashcode (2, 1);
    System.out.println("Hashcode of t1 is " + t1.hashCode());
    System.out.println("Hashcode of t2 is " + t2.hashCode());
    System.out.println("t1.equal(t2) is " + String.valueOf(t1.equals(t2)));
    }
    }