When will Runnable.toString () be able to return a duplicate string?
Thomas's answer is correct in that the Object
default method toString()
will be called, which creates different String
for different objects.
One note here. Object.toString()
returns:
return getClass().getName() + "@" + Integer.toHexString(hashCode());
It includes Object.hashCode()
. The javadoc hashCode () states:
... the hashCode method defined by the class
Object
returns different integers for individual objects ...
The key is that it hashCode()
will be different for individual objects. Since your code does not store the generated Runnable
s, once Thread
completed they will be garbage collected. After the object is removed from memory, another symbol Object
may take its place in memory, and it is possible that the new one Runnable
will provide the same hash code that was returned by the previous one Runnable
, which is now terminated .
So it is theoretically possible that you will see the same ones String
printed indeterministically (although the chances are very slim).
source to share
From the doc: A method toString()
for a class Object
returns a string consisting of the name of the class whose object is the object 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:
getClass().getName() + '@' + Integer.toHexString(hashCode())
The method used toString()
has a class Object
. And as you can see, it includes hashCode, so it will never print duplicate values, assuming all instances of your previous one Runnable
are still IN memory.
source to share