The simplest and more readable implementation of your problem is using a Comparator
instead of Comparable
. Comparable
is better suited for your own classes.
import java.util.*;
public class Sort {
public static void main(String[] args) {
String[] testArray = {
"/",
"/games/",
"/homework/",
"/usr/",
"/games/snake/",
"/temp/downloads/",
"/usr/local/",
"/usr/local/bin/"
};
Comparator<String> pathComparator = new PathComparator();
Arrays.sort(testArray, pathComparator);
System.out.println(Arrays.toString(testArray));
}
static class PathComparator implements Comparator<String> {
public int compare(String path1, String path2) {
String[] dirs1 = path1.split("/");
String[] dirs2 = path2.split("/");
if (dirs1.length < dirs2.length) {
return -1;
}
else if (dirs1.length > dirs2.length) {
return 1;
}
else {
String lastDir1 = dirs1[dirs1.length - 1];
String lastDir2 = dirs2[dirs2.length - 1];
return lastDir1.compareTo(lastDir2);
}
}
}
}
Also note that using descriptive names for variables make the code much more readable. When your code contains variables named d
, l
, arg0
etc., it becomes unreadable. For example, l
can mean length
or last
or list
. In 2 weeks you won't remember what it meant.