简体   繁体   English

使用比较器 class 创建一个数组

[英]creating an array with the comparator class

I know how to create a priority Queue with the comparator class.我知道如何使用比较器 class 创建优先级队列。 Here I created a comparator class to compare 2 characters.在这里,我创建了一个比较器 class 来比较 2 个字符。 My question is that how should I create a char array with the comparing methods?我的问题是我应该如何使用比较方法创建一个 char 数组? I tried the following: char[] helper = new char[](new StringNumComparator());我尝试了以下方法: char[] helper = new char[](new StringNumComparator()); . .

 public String Practice(String input) {
        class StringNumComparator implements Comparator<Character> {
            @Override
            public int compare(Character a, Character b) {
                if (Character.isAlphabetic(a) && Character.isAlphabetic(b)) {
                    return (int) a <= (int) b ? -1 : 1;
                } else if (Character.isDigit(a) && Character.isDigit(b)) {
                    return Character.getNumericValue(a) <= Character.getNumericValue(b) ? -1 : 1;
                }
                return Character.isAlphabetic(a) ? -1 : 1;
            }
        }

        char[] helper = new char[](new StringNumComparator());
        return new String(helper);
}

There is no such concept as an "always-sorted array" in Java like it seems you're trying to create. Java 中没有“始终排序的数组”这样的概念,就像您正在尝试创建的那样。 You could explicitly sort an array using a customer comparator:您可以使用客户比较器显式排序数组:

Arrays.sort(myArray, new StringNumComparator());

But note this only applies to arrays of objects (like Character ), not primitives (like char ).但请注意,这仅适用于对象的 arrays (如Character ),不适用于基元(如char )。

this is invalid in java:这在 java 中无效:

char[] helper = new char[](new StringNumComparator());

instead you can create the array and later sort it calling the help method (static method) of the class Arrays相反,您可以创建数组,然后调用 class Arrays 的帮助方法(静态方法)对其进行排序

char[] helper = ...your array
Arrays.sort(helper, new StringNumComparator());

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

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