简体   繁体   English

Java 自定义比较器实现

[英]Java custom Comparator implementation

I am writing a Comparator with which I can sort a String array using character count.我正在编写一个比较器,我可以使用它使用字符数对字符串数组进行排序。 The Strings are all lowercase ASCII characters.字符串都是小写的 ASCII 字符。

Eg.例如。

input = {"art", "bash", "tar"};
Expected sorted output = {"art", "tar", "bash"}; 

Here, it does not matter if "bash" is at the beginning, but "art" and "tar" should be one after the other, in no particular order as they have matching character count.在这里,“bash”是否在开头并不重要,但“art”和“tar”应该一个接一个,没有特定的顺序,因为它们具有匹配的字符数。

I have this code, where I am using a simple array to check and keep the character count and compare.我有这段代码,我在其中使用一个简单的数组来检查和保持字符数并进行比较。

Comparator<String> comparator = new Comparator<String>() {
    
    @Override
    public int compare(String s1, String s2){
        if (s1.equals(s2)) return 0;
        
        int[] a1 = getCountArray(s1);
        int[] a2 = getCountArray(s2);
        if (Arrays.equals(a1, a2)) return 0; // character count matches

        return s1.compareTo(s2);
    }

    private int[] getCountArray(String s) {
        int[] array = new int[256];
        for (int i=0; i<s.length(); i++){
            array[s.charAt(i) - 'a'] ++;
        }
        return array;
    }

};
String[] input = {"art", "bash", "tar"};
Arrays.sort(input, comparator); 

However, it does not work.但是,它不起作用。 What am I doing wrong?我究竟做错了什么?

Your comparator is not consistent:您的比较器不一致:

  • when comparing "art" against "bash" it returns that "art" is smaller than "bash"当比较“art”和“bash”时,它返回“art”小于“bash”
  • when comparing "bash" against "tar" it returns "bash" is smaller than "tar"当比较“bash”和“tar”时,它返回“bash”小于“tar”
  • therefore when comparing "art" against "tar" it must return "art" is smaller than "tar" (since "art" < "bash" < "tar"), but your comparator returns "art" is the same as "tar".因此,当比较“art”和“tar”时,它必须返回“art”小于“tar”(因为“art”<“bash”<“tar”),但比较器返回的“art”与“tar”相同”。

When you call Arrays.sort(input, comparator);当您调用Arrays.sort(input, comparator); the sort method will do pair-wise comparisons and will always find that "bash" has to be before "tar". sort 方法将进行成对比较,并且总是会发现“bash”必须在“tar”之前。

To fix this you must replace return s1.compareTo(s2) with something that compares the character count arrays a1 and a2 .要解决此问题,您必须将return s1.compareTo(s2)替换为比较字符数 arrays a1a2的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM