简体   繁体   中英

why does it print “tostring” twice?

here is my class please explain why does it prints "tostring" twice

public class HashCodeAndEquals 
{
    static String asd;

    public HashCodeAndEquals(String string) {
        asd = string;
    }


    /**
     * @param args
     */
    public static void main(String[] args) {
        HashCodeAndEquals obj1 = new HashCodeAndEquals("one");
        HashCodeAndEquals obj2 = new HashCodeAndEquals("two");
        System.out.println(obj1.toString());
        //System.out.println(obj2.toString());
        System.out.println(obj1.equals(obj2));
        System.out.println(obj1==obj2);

    }


    @Override
    public String toString() {
        // TODO Auto-generated method stub
        System.out.println("tostring");
        return "tostring";
    }

    @Override
    public int hashCode() {
        // TODO Auto-generated method stub
        System.out.println("hashcode");
        return 0;
    }

}

why does it calls toString method twice ?? at what point hash code is called and does hashcode() calls tostring() or is called by toString() ???

Don't have a System.out.println(...) call from within the toString() method as it makes no sense. The goal of this method is not to print a String but rather to return a String, one that the calling code can then decide what to do with, including printing it out, or displaying it in a GUI, or whatever.

so change this:

public String toString() {
    System.out.println("tostring");
    return "tostring";
}

to this:

public String toString() {
    return "tostring";
}

As an aside, the System.out.println method automatically calls toString() on objects it's printing, and so there's no need to explicitly call this from within the method parameter.

Thus you can change this:

System.out.println(obj1.toString());

to the more concise:

System.out.println(obj1);

As another aside, you are planning on changing your hashCode() method, right?


Regarding,

at what point hash code is called and does hashcode() calls tostring() or is called by toString() ?

Your program should tell you exactly when hashCode() is called as your override has a println within it. It will be called if you place your object in a HashSet or use it as a key to a HashMap. It is also used when checking for equality in collections (I believe), but test your code to see when and where it is used. Also make hashCode more useful by having it return non-0 values that depend on states of the key fields of your class, the same fields used in your equals method test.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM