I saw that Java has preview work on value types. Does that mean == is the right way to compare them, or should I still use Objects.equals()?
Can I use == to compare Java value types now?
Answers
Objects.equals() is still the safer general choice when you want the equality defined by a class. It handles nulls and calls equals() when the first argument is non-null.
The fact that a type is a value type doesn't automatically mean every comparison you want should use ==. Check the class's equality behavior rather than assuming that value type, immutability, and your intended notion of equality all mean the same thing.
Reply to this answer
Yes, == can be used with value types, but don't turn that into a blanket rule for objects. Java already has cases like enums where == is useful. That doesn't make it interchangeable with equals() for every class.
Reply to this answer
For an API author, the comparison behavior is part of what callers need to understand. Document it, including what equals() means for the class. Someone reading a use of == shouldn't have to guess what assumptions the code makes about the type.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Veldquari-9h:
So the useful question is what equality the particular API promises, not just whether == compiles.