I have a class with a few fields, one of which is an int, and 2 are long. What I’m thinking of doing is adding in a check in equals() so if an Integer object is passed in, it will compare the int field, and if the same return true. Likewise, if Long is passed in, if it is between the 2 long fields, it will return true.
So, if I add several of these objects to a List or Set, I can then do a get() and have it automatically give me the first object that matches. My thought is if I do this, then I simply make the get() call, and then I’ll have it, instead of having to have an extra loop & checks.
Is this a good idea or bad idea compared to simply iterating over all of the objects and doing the comparisons that way?
Don’t do this.
The
equals()method has a well-defined contract, and your proposed implementation violates it. For example, it won’t be symmetric; ifxis your object andyis anInteger,y.equals(x)will be false even whenx.equals(y)is true. Breaking these rules will confuse anyone who has to work with your code—even yourself, in the future, when you are more accustomed to using this method correctly.Your use cases sound like they could be satisfied with a
NavigableMap, where keys are integers, and values are instances of your class.