Why is hashcode called in this example?

Can someone explain why hashCode is called in the example below?

import java.util.List; public class JSSTest extends Object{ public static void main(String args[]){ JSSTest a = new JSSTest(); JSSTest b = new JSSTest(); List<JSSTest> list = new java.util.ArrayList<JSSTest>(); list.add(a); list.add(b); System.out.println(list.get(0)); System.out.println(list.get(1)); } @Override public boolean equals(Object obj){ System.out.println("equals"); return false; } @Override public int hashCode(){ System.out.println("hashCode"); return super.hashCode(); } } 

Result:

 hashCode 0 JSSTest@1bab50a hashCode 0 JSSTest@c3c749 
+6
source share
3 answers

By default, the implementation of toString() calls hashCode . This has nothing to do with lists.

Here's a pretty minimal reproduction:

 public class JSSTest { public static void main(String args[]){ JSSTest test = new JSSTest(); // Just to show it not part of creation... System.out.println("After object creation"); test.toString(); } @Override public boolean equals(Object obj){ System.out.println("equals"); return false; } @Override public int hashCode(){ System.out.println("hashCode"); return super.hashCode(); } } 

(You can override toString() to display before / super call / after details).

It is documented in Object.toString() :

The toString method for the Object class returns a string consisting of the name of the class whose object is the instance, the at-sign `@ 'character, and the hexadecimal representation of the objectโ€™s hash code. In other words, this method returns a string equal to the value:

 getClass().getName() + '@' + Integer.toHexString(hashCode()) 
+15
source
 System.out.println(list.get(0)); 

I believe this is part of the Object.toString () method that all objects have if you do not override toString () in your class. Try it and see.

+7
source

since the implementation of toString() in Object calls it.

  public String toString() { return getClass().getName() + "@" + Integer.toHexString(hashCode()); } 

Overwrite toString and it will not be called

+6
source

Source: https://habr.com/ru/post/891572/


All Articles