Which of the following method(s) must be implemented correctly if the class has to behave properly and consistently with all Java collection classes and interfaces?
A public int hashCode()
B protected Object clone()
C public String toString()
D public boolean equals(Object obj)
E public long hashCode()
F Only option E is correct
解答:
A and D are correct. The methods public int hashCode() and public boolean equals(Object obj) must be implemented correctly by a class if its objects have to behave consistently and properly with all Java collection classes and interfaces, or for that matter with any other classes. Also note that, the method hashCode() returns an int and not long. Hence option E is incorrect. Also, it is not mandatory to implement/override any other method so that the class behaves properly and consistently with all Java collection classes and interfaces.Let us understand why it is important to implement these methods correctly. The collection classes internally use these two methods of objects for performing various collection operations.  If these methods are implemented incorrectly, you simply do not know how your class objects will behave when confronted with objects of other class.For an example, if your class violates the "reflexivity" rule which says an object must be equal to itself, and then an instance of your class is added to a collection;the collection's contains method would return false indicating that the collection did not contain the instance that you just added. Also, whenever equals method is overridden in a class is necessary to override hashCode method as well, as specified by the general contract of hashCode method.

解决方案 »

  1.   

    题目不错,
    我来试着翻译一下
    对一个类来讲,要想与Java的集合类和接口保持一致并运行无误,必须实现下面的那个(些)方法?A和D是正确的 。
    也要注意,hashCode()返回的是int型而不是long型,所以另外,要想与Java的集合类和接口保持一致并运行无误,任何其他方法都不是必须要实现的,所以。。那么为什么这两个方法是必须要实现的呢?这是因为集合类内部使用这两个方法进行各种集合操作,如果这两个方法没有实现正确,那么当遇到其他类的对象时,你的对象就不知所措了。例如,如果你的类违反了“自反性”,也就是一个对象必须等于他自身,那么当你的类的实例被添加到一个集合中时就会返回false,这意味着集合中并没有包含你刚刚添加的对象。另外,无论何时,只要equals方法被重写了啦,那么hashCode方法也必须要重写。(这其实在《Effective Java》一书中第8条有明确解释,译者注)