Firstly, your method is incorrect. You are counting on a string representation of classes that have not redefined the toString() method from Object .
The Object.toString method, if not overridden, returns a string consisting of the class name, @ and the hash code object. This is not his address; he has nothing to do with the address. Therefore, two objects with the same hash code will return the same string.
To demonstrate this, consider a small class that overrides equals and hashCode , but does not override the toString method:
class MyInteger { int myInteger; public MyInteger(int myInteger) { this.myInteger = myInteger; } public int getInteger() { return myInteger; } @Override public boolean equals(Object obj) { if ( obj instanceof MyInteger ) { return myInteger == ((MyInteger)obj).myInteger; } return false; } @Override public int hashCode() { return myInteger; } }
Now try your method of selecting two different objects:
MyInteger int1 = new MyInteger(1004); MyInteger int2 = new MyInteger(1004); System.out.println(int1+" "+int2);
The result will look something like this:
MyInteger@3ec MyInteger@3ec
But it is clear that int1 and int2 point to two different objects explicitly created with new !
So forget this method - it does not make sense.
Now, how do you know that two objects are different? Simple, compare links with == or != .
So if I tried above
System.out.println( int1 != int2 );
The result will be true .
Same for strings:
String a="helloworld"; String b="hello"; String c=b+"world"; String d="hello"; System.out.println("a refers to a different object than c? " + (a != c)); System.out.println("b refers to a different object than d? " + (b != d));
Printed Results:
a refers to a different object than c? true
b refers to a different object than d? false