This is easy: never convert to strings. Try deepEquals it should do what you want, although you of course first have to dive into your myArray and iterate over the elements.
public static boolean contains(String[][][] set, String[][] obj) {
for (String[][] elt : set) {
if (Arrays.deepEquals(elt, obj)) {
return true;
}
}
return false;
}
This performs the contains function for your test set in about 4.5% of the time.
Java has type erasure when it comes to arrays over objects (including other arrays). As such it may be slightly faster to create deepEquals(String[][], String[][]) yourself where you use Arrays.equals(String[], String[]), as you would not have to check if the objects are arrays of String at runtime, nor would you have to check if there are any arrays nested even deeper.
public static boolean fasterContains(String[][][] set, String[][] obj) {
for (String[][] elt : set) {
if (deepEquals(elt, obj)) {
return true;
}
}
return false;
}
private static boolean deepEquals(String[][] a, String[][] b) {
int n = a.length;
if (b.length != n) {
return false;
}
for (int i = 0; i < n; i++) {
if (!Arrays.equals(a[i], b[i])) {
return false;
}
}
return true;
}
This performs the contains function for your test set in about 3.5% of the time, while being only slightly more complex than the test above.
As a general hint: computers are not efficient when it comes to Strings (although newer Java versions did address this somewhat). Anyway, never convert to string for any comparison, calculation, concatenation or whatnot. Always compare bytes, integers or objects (i.e. the original data) unless there is really no other way.
If you just have a list of characters then there are two observations:
char[][] should also work;
- or just a
String[] of course, where the String consist of the various characters (which you can retrieve using String#charAt(index) and compare using String#equals(other).
With the latter you can bring down the search time to about 2%.