I am having trouble compiling some code that I wrote. The code is meant to sort an array of directories, and then return the sorted array. The arrays being passed into the program look like this: {"/","/usr/","/usr/local/","/usr/local/bin/","/games/","/games/snake/","/homework/","/temp/downloads/"}
The sorted answer for this would be:
{ "/", "/games/", "/homework/", "/usr/", "/games/snake/",
"/temp/downloads/", "/usr/local/", "/usr/local/bin/" }
So basically, the directories which are the least deep are placed first. If two directories have the same depth, we sort alphabetically depending on the first word. My code so far is this:
import java.util.Arrays;
import java.util.Comparator;
public class Dirsort {
class APTComp implements Comparator<String> {
public int compare(String a, String b) {
String[] d1 = a.split("/");
String[] d2 = b.split("/");
int diff = d1.length - d2.length;
if (diff != 0) {
return diff;
} //{"/","/usr/","/usr/local/","/usr/local/bin/","/games/","/games/snake/","/homework/","/temp/downloads/"}
return a.compareTo(b);
}
public String[] sort(String[] dirs) {
Arrays.sort(dirs);
return dirs;
}
}
Can you guys tell me anything you find wrong here? Does my Arrays.sort() call use my modifiend compare method?
Thanks a lot, Junaid