Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Annotating a Java class as safe for reference comparison

I have a class that's a multiton, so I know that given a particular key, there will never be two instances of the same class that exist. This means that, instead of:

if (someObject.equals(anotherObject))

...it's safe for me to do this:

if (someObject == anotherObject)

The class is also final, so I know that nothing related to polymorphism could cause problems for comparison either.

IDEA dutifully informs me that it's risky to compare two instances directly and that I should use .equals(), but I know it's not in this case. Is there some annotation I can apply to my class to instruct IDEA, and potentially other editors and more importantly other users, that a direct reference comparison for equality on instances of my class is safe?

I know I could just tell IDEA to suppress the warning, but I'd have to do it for every comparison between these two types or globally, neither of which is a good idea. Plus, it's more important that I let users of my class know it's safe, faster, and even preferred (convince me otherwise) over .equals().

like image 688
user3466413 Avatar asked Mar 03 '15 18:03

user3466413


1 Answers

The IntelliJ inspection has an option "Ignore '==' between objects of a type with only private constructors". If I understand correctly, enabling this option will turn off the highlighting in your case.

There is currently no possibility in IntelliJ IDEA to ignore the == comparison based on an annotation.

like image 72
yole Avatar answered Oct 22 '22 16:10

yole