Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why hashcode is called in this example?

Tags:

java

hashcode

Can someone please 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();
    }
}

Outcome:

hashCode 0
JSSTest@1bab50a
hashCode 0
JSSTest@c3c749
like image 512
JSS Avatar asked Jun 28 '11 16:06

JSS


1 Answers

The default toString() implementation calls hashCode. This has nothing to do with lists.

Here's a fairly minimal repro:

public class JSSTest {

    public static void main(String args[]){
        JSSTest test = new JSSTest();
        // Just to show it's 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 could override toString() to display before / super call / after details, too.)

It's documented in Object.toString():

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

getClass().getName() + '@' + Integer.toHexString(hashCode())
like image 51
Jon Skeet Avatar answered Oct 05 '22 03:10

Jon Skeet