1

I know how to create a priority Queue with the comparator class. Here I created a comparator class to compare 2 characters. My question is that how should I create a char array with the comparing methods? I tried the following: 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);
}

2 Answers 2

2

There is no such concept as an "always-sorted array" in Java like it seems you're trying to create. 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).

Sign up to request clarification or add additional context in comments.

Comments

1

this is invalid in 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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.