From just the perspective of “sorting three strings”, you could just need to do three comparisons and lose all those temp variables.
public static void stringOrder(String a, String s, String d) {
String tmp;
if (a.compareTo(s) > 0) {
tmp = a;
a = s;
s = tmp;
}
if (a.compareTo(d) > 0) {
tmp = a;
a = d;
d = tmp;
}
if (s.compareTo(d) > 0) {
tmp = s;
s = d;
d = tmp;
}
sayName(a, s, d);
}
But from a maintainability perspective, just use the facilities built into Java to sort multiple strings at a time:
public static void stringOrder(String a, String s, String d) {
String [] arr = {a, s, d};
java.util.ArrayList<String> list = new ArrayList<String>(Arrays.asList(arr));
java.util.Collections.sort(list);
sayName(list.get(0), list.get(1), list.get(2));
}
0
solved How can I shorten this Java code? [closed]