Reputation: 3413
In the middle of a refactoring, I've noticed that anything (because it's inherited from Object) can be compared using the equals()
method, but I want to call a method that only compares Strings, because that would let the compiler stop me if I'm comparing objects of different types.
There's any built-in method in Java that do this?
Upvotes: 0
Views: 70
Reputation: 1851
@Julio Rodrigues you can use the method contentEquals()
string1.contentEquals(string2)
It's case sensitive, and it's only present in the class String (not inherited from object),.
Upvotes: 1
Reputation: 109597
Use FindBugs, static code analysis, quite easy; with IDE plugins, with separate GUI app. That will mark such problematic uses and others.
That is a better shot-gun approach: repeatable and finding several issues. Absolute fun.
Upvotes: 0
Reputation: 20520
If you need something that returns a boolean
, you can write your own static method that takes two String
instances and uses .compareTo()
or .equals()
behind the scenes. If the signature requires String
s, the compiler will enforce it.
public static boolean compareStrings(String a, String b) {
return a.equals(b);
}
This will throw a NullPointerException
if a
is null
, which may or may not be what you want. It would be easy enough to put in a check.
Upvotes: 1