This is not a "please do my homework" question. I solved a problem two ways and would like to know which solution is better; better being defined by better readability, lower complexity and lower memory consumption. I'd also like to note that this is a not a homework assignment but an optional no-credit practice problem.
My CS class offers practice problems through their site. One specific question is named "removeShorterStrings." The prompt being:
Write a method removeShorterStrings that takes an ArrayList of Strings as a parameter and that removes from each successive pair of values the shorter string in the pair. For example, suppose that an ArrayList called list contains the following values:
{"four", "score", "and", "seven", "years", "ago"}
In the first pair, "four" and "score", the shorter string is "four". In the second pair, "and" and "seven", the shorter string is "and". In the third pair, "years" and "ago", the shorter string is "ago". Therefore, the call: removeShorterStrings(list); should remove these shorter strings, leaving the list as follows: "score", "seven", "years". If there is a tie (both strings have the same length), your method should remove the first string in the pair. If there is an odd number of strings in the list, the final value should be kept in the list.
I have come up with the following solutions:
The "ask for permission" solution:
void removeShorterStrings(ArrayList<String> list) {
if (list.size() != 0) {
int isOdd = (list.size() >> 0) & 1;
for (int i = 0; i <= (list.size() >> 1) - isOdd; i++) {
String first = list.get(i);
String second = list.get(i + 1);
if (first.length() <= second.length()) {
list.remove(i);
} else {
list.remove(i + 1);
}
}
}
}
and the "ask for forgiveness" solution:
void removeShorterStrings(ArrayList<String> list) {
for (int i = 0; i <= (list.size() >> 1); i++) {
try {
String first = list.get(i);
String second = list.get(i + 1);
if (first.length() <= second.length()) {
list.remove(i);
} else {
list.remove(i + 1);
}
} catch (IndexOutOfBoundsException e) {
break;
}
}
}
I come from a JavaScript/python background, so I'm unsure of what is considered "good practice" in java.
TL;DR: Which solution is better in terms of better readability, lower complexity and lower memory consumption?