Overiding compareTo in Comparable for sorting
介绍
我正在尝试为字符串数组创建自定义排序方法,但是由于某些原因,我的代码无法正常工作。 我正在编写的方法将接受这样的输入
1 2 3 4 5 6 7 8 | {"/", "/games/", "/homework/", "/usr/", "/games/snake/", "/temp/downloads/", "/usr/local/", "/usr/local/bin/"} |
我想排序如下:
我的密码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import java.util.*; public class Dirsort { public String[] sort(String[] dirs) { ArrayList<Sort> mySort = new ArrayList<Sort>(); for (String d: dirs){ String l = d.split("/")[-1]; int di = d.length(); mySort.add(new Sort(di,l,d)); } Collections.sort(mySort); String [] ans = new String [mySort.size()]; int count = 0; for (Sort s: mySort){ ans[count] = s.toString(); count++; } return ans; } class Sort implements Comparable<Sort>{ private int d; private String last; private String dir; public Sort(int myD, String myLast, String myDir){ d = myD; last = myLast; dir = myDir; } public String toString(){ return dir; } @Override public int compareTo(Sort arg0) { // TODO Auto-generated method stub if (this.d == arg0.d){ return this.last.compareTo(arg0.last); } return this.d-arg0.d; } } } |
问题
我在测试代码时收到以下错误,但我不知道为什么。
runtime exception:java.lang.ArrayIndexOutOfBoundsException:
-1java.lang.ArrayIndexOutOfBoundsException: -1 at Dirsort.sort(Dirsort.java:6) at Tester$1.run(Tester.java:48) ["/",
"/usr/","/usr/local/","/usr/local/bin/","/games/","/games/snake/",
"/homework/","/temp/downloads/" ]
您的问题最简单易读的实现是使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | 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); } } } } |
还要注意,对变量使用描述性名称会使代码更具可读性。 当您的代码包含名为
您不能在Java中使用