Predictably same Object.hashCode()
of totally different instances
If I understand correctly, then the Object.hashCode()
of each new instance of the object should be new and almost always different from the previous ones, with the exception of a collision.
But I found an interesting pattern.
If I use Android Studio, create an Activity and call the hashcode in the onCreate
, onStart
, onResume
, onPause
, onStop
, onRestart
, onDestroy
methods and run the application in the emulator, then I get the same hashcode in the logs under the following conditions:
onStart
, onResume
, onPause
, onStop
, onRestart
cycle.The only requirement for the hashcode method is that if two objects are equal then they must have the same hashcode. There is no warranty that two objects that differ should have different hashcodes. If a class doesn't override the hashcode method then the behavior is implementation dependent. A typical behavior is to return the internal object reference. If the activity is the first to run in your emulator then is not that strange if it would always get the same object reference (which could be a simple counter). Of course if you close and rerun the app in the same emulator session you will get a new object reference and so a new hash. Swiping kills the vm process, so a new vm is started and the object reference counter is reset.
https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#hashCode()