So I did not fully understand how hashCode Overridng Works, so I searched for a tutorial on a hashCode Overriding. I found a tutorial where I learned the concept of a hashCode, same object must have same hashCode( but that does not mean that different objects must have diffrent hashCode). What I did not understand is his implementation of the hashcode:
@Override
public int hashCode() {
int hash = 7;
hash = 31 * hash + Objects.hashCode(this.myShirtColor);
return hash;
}
What i do not understand here is what will Objects.hashCode(this.myShirtColor) give? myShirtColor is a String.
Ok first you need to understand two things String immutability and String Pool .
String immutability
it means that the content of the String Object can't be changed, once it is created.
String Pool
The Java string constant pool is an area in heap memory where Java stores literal string values. The heap is an area of memory used for run-time operations. When a new variable is created and given a value, Java checks to see if that exact value exists in the pool.
Let's sum up both together in a sample , assuming String strOne="abc";
the abc
value is created once ( String Immutability ) and stored on the string pool in heap ( String Pool ), Ok so what if I do another string String strTwo= "abc";
on the same JVM the compiler will check the pool if it abc
is exist which is true then it is retrieved.
That means: strOne == strTwo
is true
since both refer to the same object
Ok back to hashcode you can see now if 2 object on your case has the same shirtColor
will have the same hashcode
if shirtColor="blue"
for example Then right after you have an object eg shirt1
of your class -you did not mention- but assuming Shirt
class a blue
value string is stored in heap if you created another object of class Shirt
with color "blue"
eg shirt2
, the blue
value will be fetched from string pool the very exact same object as shirt1
's shirtColor
if you then called the hashCode
for both objects it will be the same since it depends on the very exact object "blue"
.
Objects.hashCode
is a simple function that does check object if null returns 0 otherwise returns object's hashCode
https://docs.oracle.com/javase/7/docs/api/java/util/Objects.html#hashCode(java.lang.Object)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.