+ 3

Can anyone explain me what is the difference between object reference and hash code in Java

I studied in strings that object reference is the unique hexadecimal number representing the memory address of object , and now when I am studying hash code I am coming to that hash code is just a unique number alloted to objects by jvm and is also called a reference number , so is hashCode(reference number) any way related to object reference and if not ,what is use of hashCode and in the book "core Java" besides hashCode in the bracket they are writing object reference what is explaination for that Pls explain me I am little confused with this

24th Apr 2020, 3:05 PM
Shubham Pandey
Shubham Pandey - avatar
2 odpowiedzi
+ 1
String s1 = new String("Shubham"); String s2 = new String("Shubham"); In these two lines, we create two instances of String objects. They exist separately, so they occupy different parts of the memory, so have different reference. But they contain the same value, therefore their hashCode is the same. hashCode is an integer number that is intended to signify the uniqueness of your objects. If two objects are equal, they must also have the same hashcode. If you create your own class and you want to put it in a hashable collection, for example HashSet<MyClass> then MyClass must implement the hashcode method. These data structures that work with hash tables, allow for very quick data retrieval. Further read: https://www.baeldung.com/java-hashcode
24th Apr 2020, 4:06 PM
Tibor Santa
Tibor Santa - avatar
0
Thanks so much
24th Apr 2020, 5:23 PM
Shubham Pandey
Shubham Pandey - avatar