What is the best way (algorithm) to implement the hashCode method?
What is the consequence of not implementing the hashCode method and
say addiding it to a Set?



On Apr 15, 3:14 pm, Mihai DINCA <[email protected]> wrote:
> Hi Cecil
>
> Java says that if a.equals(b) is true, than a.hashCode() must be
> identical to b.hashCode(). I.e. two objects are equal if and only if
> their hasCode are equal.
>
> The hashCode() is internally used by various library classes, for e.g.
> all the hashtable based collections.
>
> Let's say you have a HashSet and two different String objects:
> HashSet h = new HashSet();
> String str1 = args[0];
> String str2 = args[1];
>
> Then you add the two strings to the HashSet:
> h.add(s1); h.add(s2);
>
> If the content of s1 is identical to s2 (for e.g. they both contain
> "Hello World"), then the HasSet will contain only one element. This
> happens because hashCode() is overriden in the String class in order to
> be compatible with the "equals" method and the HashSet is based on the
> hashCode of the added objects.
>
> You must use @Override since Java 5 (is is not mandatory, you get a
> warning only if you don't do it). This is a supplementary protection
> against mistakes. If you define a method "equals" but you didn't want to
> override the original one (you just forgot there is a standard "equals"
> method), then you get a warning. If you want to override the original
> "equals" but you misspell the name, such as "@Override ... eguals(Object
> o) ..." or you have errors in the definition, such as "@Override ...
> equals(Person p) ..." (it is an error, because it is not an override:
> the original method is ... equals(Object o) ...", then you get an error
> message. So you have more notifications at compile time and less
> surprises at execution time.
>
> Hope it helps
> mihai
>
> PS: I saw the example "@Override ... equals(Person p) ..." somewhere, I
> think it was just in the @javapassion course
>
> Cecil H a écrit :
>
> > Exercise 5.1 class Card3.java and method hashCode(), whats the purpose
> > of this method its not called from anywhere? Is it also necessary to
> > add the @Override  to the methods: public boolean equals(Object obj),
> > public int hashCode(), public String toString()
>
> > The program runs fine. I'm thinking the hashCode method may have been
> > put in there to randomize the cards and suit, if user input was used.
> > But since we explicitly declare the card and suit in the main method,
> > its kind of pointless.
>
> --
> To post to this group, send email to 
> [email protected]
> To unsubscribe from this group, send email to 
> [email protected]
> For more options, visit this group 
> athttp://groups.google.com/group/javaprogrammingwithpassion?hl=en

-- 
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/javaprogrammingwithpassion?hl=en

Reply via email to