we know that each object has a hash value?Is it true to say that can a object have multiple values?any sample program on this concept?
thanks venkat
Alex Belisle Turcot
Ranch Hand
Joined: Apr 26, 2005
Posts: 516
posted
0
Hi,
To my knowledge, as long as the object as the same reference, its hashCode will remain the same during the program's life.
And, its hashCode is unique during the program's life.
That's what I think, Alex
Ariel Ortiz
Ranch Hand
Joined: May 14, 2004
Posts: 121
posted
0
The value returned by hashCode doesn't have to remain the same during the program's lifetime. The hashCode of a class should be computed using the same field values that the equals method uses to determine object equality. So, if the internal state of an object changes so should its hash value. A simple example:
If you run the following code:
The expected output would be:
It's important to point out that if you effectively plan to use instances a class as keys for a Map structure, that class should better be designed to be immutable, otherwise you might be unable to retrieve the associated value if the key happens to mutate. That's why we usually use Strings and Integers as Map keys, because we cannot change the internal state of these objects.
By the way, the behavior stated by Alex is only true if your class doesn't override the hashCode method inherited from the java.lang.Object class.
Being a little bit more precise, the API states: [The hashCode method] is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java programming language.
...Ariel
Alex Belisle Turcot
Ranch Hand
Joined: Apr 26, 2005
Posts: 516
posted
0
ok, well after those 2 posts on hashCode, I feel I have to go back to this section of my book
Please go your "my profile" link and change your display name again, you must use your real first and last names. There are two fields, one for your first name and one for your last name.
The value returned by hashCode doesn't have to remain the same during the program's lifetime. Assuming you mean "object lifetime", yes it does, otherwise, the contract is broken. "Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, ..."
Hello Tony,
I did mean "object lifetime". Yet the ellipsis you omited for the hashCode API says: provided no information used in equals comparisons on the object is modified.. This is exactly what is was refering:
My full quote:
The value returned by hashCode doesn't have to remain the same during the [object's] lifetime. The hashCode of a class should be computed using the same field values that the equals method uses to determine object equality. So, if the internal state of an object changes so should its hash value.
I do suggest you read the full context before stating that someone is wrong.