5
package javaLearning;
import java.util.Arrays;
import java.util.Collections;

    public class myarray {

         public static void name() {
         String hello;
         hello = "hello, world";
         int hello_len = hello.length();
         char[] hello_array = new char[hello_len];
         hello.getChars(0, hello_len, hello_array, 0);
         Arrays.sort(hello_array, Collections.reverseOrder());
}

the "myarray" class is defiend in a main method of a testing class. why does it give me a compile error when I try reversing the array?

3
  • 2
    And what is haa? Please post your actual code. Commented Apr 7, 2011 at 16:45
  • Exception in thread "main" java.lang.RuntimeException: Uncompilable source code Commented Apr 7, 2011 at 16:47
  • since that apparently you're learning Java you should know that the official guidelines favors the use of all-lowercase package names. Prefer javalearning to javaLearning. Commented Apr 7, 2011 at 16:53

6 Answers 6

6

Collections.reverseOrder() returns a Comparator<Object>. And Arrays.sort with comparator doesn't work for primitives

This should work

import java.util.Arrays;
import java.util.Collections;

public class MyArray {

    public static void name() {            
        String hello = "hello, world";
        char[] hello_array = hello.toCharArray();
        // copy to wrapper array
        Character[] hello_array1 = new Character[hello_array.length];
        for (int i = 0; i < hello_array.length; i++) {
           hello_array1[i] = hello_array[i];
        }
        // sort the wrapper array instead of primitives
        Arrays.sort(hello_array1, Collections.reverseOrder());                            
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

The error I get (assuming the original post had some typos) is that Collections.reverseOrder() returns a Comparator<Object>.

Arrays.sort (with a compartor) is only defined for descendents of Object so doesn't work for primitive types.

Comments

0

You forgot to declare haa = hello.getChars(0, hello_len, hello_array, 0);

Comments

0

Use Arrays.sort to sort in ascending order, then reverse the elements of the array (can be done inline with a simple loop).

Comments

0

The first thing is that the code is not followed the standards of JAVA language. Class name should always starts with UPPER case, and sort() of Arrays should not take primitive list of values as a parameter. change the 'char' to 'Character' and then use Arrays.sort method

Comments

-1

haa is not defined in the code you have shown us. That is a compile error.

1 Comment

Ok, I have fixed the typo in the code and it is still giving me an error?

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.