java - why does it print "tostring" twice? -


here class please explain why 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 calls tostring method twice ?? @ point hash code called , hashcode() calls tostring() or called tostring() ???

don't have system.out.println(...) call within tostring() method makes no sense. goal of method not print string rather return string, 1 calling code can decide with, including printing out, or displaying in gui, or whatever.

so change this:

public string tostring() {     system.out.println("tostring");     return "tostring"; } 

to this:

public string tostring() {     return "tostring"; } 

as aside, system.out.println method automatically calls tostring() on objects it's printing, , there's no need explicitly call within method parameter.

thus can change this:

system.out.println(obj1.tostring()); 

to more concise:

system.out.println(obj1); 

as aside, planning on changing hashcode() method, right?


regarding,

at point hash code called , hashcode() calls tostring() or called tostring() ?

your program should tell when hashcode() called override has println within it. called if place object in hashset or use key hashmap. used when checking equality in collections (i believe), test code see when , used. make hashcode more useful having return non-0 values depend on states of key fields of class, same fields used in equals method test.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -