日期:2014-05-20  浏览次数:20574 次

关于一个“变态”面试题的疑问
有一个流传的变态级的JAVA程序员面试32问,我见过几次。
其中有一个问题是这样的:

两个对象值相同(x.equals(y)==true),但却可有不同的hashcode,这句话对不对?
我以为这句话是对的;但是,看到几处给出的答案都是:

不对,有相同的hashcode.

难道我理解错了题目的意思。
我是这样想的:
自定义的一个类可以重载equals和hashCode方法,我可以在equals方法里任何情况都返回true,但hashCode里用当前时间的毫秒数作为返回值:这样,很明显的,对大多数的对象x.equals(y)==true但x.hashCode()   !=   y.hashCode().

当然,这样的重载是很有问题很不符合设计思想也没有什么实际用处的。但题目说的只是可能,难道不是么?

------解决方案--------------------
现在面试他妈的都一样。那些面试的人把我们当猴耍,我面试的时候,也一样。问的那问题怪的很,可能永远也不会用到那。面试完了,人家说还可以,只是有些知识掌握的不是很好。所以工资给的不是很高。我想算了,先干吧。谁知道他妈的,进来后问他面试我时,我没回答上来的几个问题时,他说了半天也说不出来。原来他也不会。就是这么贱!!!
------解决方案--------------------
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。这个题目本身也是没事找事
------解决方案--------------------
赫赫, 是可以做到的,但是不推荐这样做

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)));
}
}