2

I'm trying to think of an easy way to create Intent request codes that prevents potential duplication of request codes across an application.

Does using Class.hashCode() sound like a bad idea to anyone?

¯\_(ツ)_/¯

public class SomeClass {

    public static final int INTENT_REQUEST_CODE_FOR_SOME_CLASS = SomeClass.class.hashCode();
}
dell116
  • 5,835
  • 9
  • 52
  • 70
  • Java does not seem to offer an airtight guarantee that two distinct hash codes on two unequal objects must be different. At least, not according to this: "It's a popular misconception that hashCode provides a unique identifier for an object. It does not." http://www.javapractices.com/topic/TopicAction.do?Id=28 or this: https://stackoverflow.com/a/1063100/3482621 – albert c braun Jun 13 '17 at 21:30
  • Also, if an app instantiates such a class in two different processes (which could in theory happen if the app were running an android service in a separate process) the hash codes will likely be different for the two instantiations since they're created in two different Java VMs. – albert c braun Jun 14 '17 at 03:38
  • @albertbraun - Both are very good explanations on why this might be a bad idea. Thank you very much. Maybe something as simple as a class with static constants would be best for this scenario. – dell116 Jun 14 '17 at 11:14
  • No prob. Those are just simply the worst things I could think of. But they don't seem horrendously bad. They just mean there's a bit of uncertainty/doubt with the technique. When I first understood your idea I thought it was pretty clever. And, though I have not tried to do any probability calculation, I guess your idea would work ok for a long time before a meaningful collision happened. (The sheer number of people running the app would also matter). But maybe there are better ideas. Maybe something similar to IntelliJ's serialVersionUID generator, some sort of script in the IDE? – albert c braun Jun 14 '17 at 15:16

0 Answers0