Reputation: 2317
I am coding in Java and I understand well that I can compare most arrays with Arrays.equals
, and I can compare strings case insensitively with String.equalsIgnoreCase
, but is there a way to specifically compare Arrays of strings case insensitively?
sample code:
class Foo {
String[] array; // don't care about case
@Override
public boolean equals(Foo obj) {
// bunch of stuff to check equality
if (!Arrays.equals(array, obj.array)) return false; // case insensitive?
return true;
}
}
Upvotes: 1
Views: 5286
Reputation: 11377
For things like that I keep a Utility class where i define a static comparator method (as String[] case insensitive comparison is not a Type specific logic and can be reused somewhere else in the program).
public static boolean caseInsensitiveCompare(String[] array1, String[] array2) {
// validate arguments
condition(allNotNullOrEmpty(array1) && allNotNullOrEmpty(array2));
if (array1 == array2) return true;
if (array1.length != array2.length) return false;
for (int i = 0; i < array1.length; i++) {
if (!array1[i].equalsIgnoreCase(array2[i])) return false;
}
return true;
}
P.S. instead of writing this
if (!Arrays.equals(array, obj.array)) return false; // case insensitive?
return true;
write this
return !Arrays.equals(array, obj.array);
or use Intellij :)
Upvotes: 1
Reputation: 37053
Your code wont compile as you are not overriding the Object's equals method which has signature like public boolean equals(Object obj)
Also to do comparison, you could do the following in your modified equals as below:
if (array == foo.array) {
return true;
}
if (array == null || foo.array == null) {
return false;
}
int length = array.length;
if (foo.length != length)
return false;
for (int i=0; i<length; i++) {
String string1 = array[i];
String string2 = foo.array[i];
if (!(string1==null ? string2==null : string1.equalsIgnoreCase(string2)))
return false;
}
return true;
Upvotes: 1