Search code examples
androidandroid-activityhashcode

Activity Object.hashCode() is the same on different instances


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:

  • Every Run of Activity in Android Studio, even if I close the emulator and Studio and go back in, and even if I restart the computer (Windows 10), but if I cold boot the emulator, the hashcode changes.
  • In the emulator itself, of course, the hashcode does not change while the Activity goes through the onStart, onResume, onPause, onStop, onRestart cycle.
  • If I close the application with the Back button and run it again in the emulator, the Hashcode changes.
  • If I kill the application by swiping it out from the recent apps screen and start it again - the hashcode becomes the same as when it was first launched.

Solution

  • 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()