I have a custom cla开发者_高级运维ss called Position. I want to use the following:-
Set<Position> s=new HashSet<Position>();
Do I have to override the HashCode() method in the Position class? I have not overridden equals() method. I want two Position objects to be considered equal only when they are the same object. Do I still have to override HashCode() in order to use the HashSet as shown above?
You only have to override hashcode
and equals
if you want different objects (presumably representing the same thing) to count as equal.
(To clarify, if you do override one you should override the other, so that objects that test as equal always have the same hashcode.)
Yes! Overwriting one of the two but not the other is very bad style and will create subtle bugs that are hard to debug. There is a contract that is documented in the JavaDoc of Object [1] and this contract should be obeyed in your own interest. If you want to read more about this, read item 7 of the very good book Effective Java [2].
- [1] http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Object.html
- [2] http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf
Edit: Sorry, I read wrong. If you are not overwriting one of them, you don't have to do anything. Still, read the item in the book. It is always a good idea to implement these both methods.
If you were using a Map, then there is a special class called IdentityHashMap which is built specifically for this purpose, i.e using reference-equality in place of object-equality when comparing keys.
精彩评论