Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct alternative to Java's equalsIgnoreCase?

There are lots and lots of examples on why and when java.lang.String.equalsIgnoreCase will fail because of incorrect use of the locale.

But I did not find any examples of the correct way. Unlike java.lang.String.toUpperCase there is no version with a locale parameter. Converting both strings to upper or lower case seem to be wasteful. Especially when you are working on a application doing a lot of comparisons.

What is the correct way to make a ignore case string comparison, taking both locale and performance into consideration?

like image 516
Martin Avatar asked Oct 30 '14 07:10

Martin


1 Answers

According to this page, you can use Collator to do case insensitive equality as follows:

//retrieve the runtime user's locale
Locale locale = new Locale(getUserLocale());

//pass the user's locale as an argument
Collator myCollator = Collator.getInstance(locale);

//set collator to Ignore case but not accents
//(default is Collator.TERTIARY, which is
//case sensitive)
myCollator.setStrength(Collator.SECONDARY);

int i = myCollator.compare(stringA,stringB);

(Copied from the above site ...)

Obviously, in other contexts you might choose the locale differently.


For @fge - This Oracle Bug Report gives an example of the kind of thing that happens.

  • http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4425387
like image 158
Stephen C Avatar answered Oct 03 '22 16:10

Stephen C