我在编写一些我编写的代码时遇到了问题。该代码用于对目录数组进行排序,然后返回已排序的数组。传递给程序的数组如下所示:{"/","/usr/","/usr/local/","/usr/local/bin/","/games/","/games/snake/","/homework/","/temp/downloads/"}
对此的排序答案是:
{ "/", "/games/", "/homework/", "/usr/", "/games/snake/",
"/temp/downloads/", "/usr/local/", "/usr/local/bin/" }
所以基本上,首先放置最深的目录。如果两个目录具有相同的深度,我们将根据第一个单词按字母顺序排序。 到目前为止我的代码是:
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;
}
}
你能告诉我你在这里发现的任何错误吗?我的Arrays.sort()调用是否使用我的modifiend比较方法?
非常感谢, Junaid
答案 0 :(得分:2)
默认情况下,Arrays.sort()方法使用自然顺序进行排序。由于您的案例中的数组是String,因此默认情况下它将根据字符串的字母顺序进行排序。
要获得所需的结果,您必须将自定义比较器实现的实例传递给Arrays.sort()。
将public String[] sort(String[] dirs)
课程中的APTComp
方法替换为:
public String[] sort(String[] dirs)
{
Arrays.sort(dirs, new APTComp());
return dirs;
}
答案 1 :(得分:0)
除非你打电话,否则Arrays.sort不会直接按你的比较器排序。你应该使用
Arrays.sort(dirs, new APTComp());
修订后的代码:
import java.util.Arrays;
import java.util.Comparator;
public class Main {
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, new APTComp());
return dirs;
}
public static void main(String[] args) {
Main main = new Main();
String[] result = main.sort(new String[] {"/","/usr/","/usr/local/","/usr/local/bin/","/games/","/games/snake/","/homework/","/temp/downloads/"});
for(int i=0; i<result.length; i++) {
System.out.println(i + ": " + result[i]);
}
}
}
结果: 0:/ 1:/游戏/ 2:/作业/ 3:/ usr / 4:/ games / snake / 5:/ temp / downloads / 6:/ usr / local / 7:/ usr / local / bin /
答案 2 :(得分:0)
此代码正常运行,请检查
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;
}
return a.compareTo(b);
}
public String[] sort(String[] dirs) {
Arrays.sort(dirs);
return dirs;
}
}
public static void main (String[] args) {
String[] arr = new String[] {"/","/usr/","/usr/local/","/usr/local/bin/","/games/","/games/snake/","/homework/","/temp/downloads/"};
Dirsort ds = new Dirsort();
Arrays.sort(arr, ds.new APTComp());
for (String s : arr) {
System.out.println(s);
}
}
}
输出:
/
/游戏/
/功课/
在/ usr /
/游戏/蛇/
/温度/下载/
在/ usr /本地/
/ usr / local / bin /