Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting array of char using Arrays.sort

Tags:

java

I'm trying to sort array of char using Arrays.sort function. I'm using the following code:

class Solution {
    public String customSortString(String S, String T) {
        Map<Character, Integer> poses = new HashMap<>(S.length());

        for(int i = 0 ; i < S.length() ; i++){
            poses.put(S.charAt(i), i);
        }

        char[] tmpArr = T.toCharArray();

        Arrays.sort(tmpArr , new Comparator<Character>(){ 

            @Override
            public int compare(Character c1, Character c2) {   
                Integer aPos = poses.get(c1);
                Integer bPos = poses.get(c2);

                if(aPos == null || bPos == null)
                    return 0;

                return Integer.compare(aPos,bPos);
            } 
        });

        return new String(tmpArr);

    }
}

But I'm getting this error:

Error:(14, 19) java: no suitable method found for sort(char[],<anonymous java.util.Comparator<java.lang.Character>>)
    method java.util.Arrays.<T>sort(T[],java.util.Comparator<? super T>) is not applicable
      (inference variable T has incompatible bounds
        equality constraints: char
        upper bounds: java.lang.Character,java.lang.Object)
    method java.util.Arrays.<T>sort(T[],int,int,java.util.Comparator<? super T>) is not applicable
      (cannot infer type-variable(s) T
        (actual and formal argument lists differ in length))

What am I doing wrong? It looks like there is no auto unboxing to Character. How can I make this work?

like image 228
restfulblue Avatar asked Oct 18 '25 22:10

restfulblue


1 Answers

char[] tmpArr = T.toCharArray();

Here is the mistake, you can't use premitives with comparator. You need to convert it to Character[].

You could do something like below with Apache commons-lang:

char[] charArray = str.toCharArray();
Character[] tmpArr = ArrayUtils.toObject(charArray);

Here are some good ways to convert.

like image 125
Krupal Shah Avatar answered Oct 20 '25 11:10

Krupal Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!