Reputation: 11673
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?
Upvotes: 5
Views: 14671
Reputation: 2800
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
Upvotes: 0
Reputation: 3084
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());
}
}
Upvotes: 6
Reputation: 53694
Use Arrays.sort to sort in ascending order, then reverse the elements of the array (can be done inline with a simple loop).
Upvotes: 0
Reputation: 44706
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.
Upvotes: 2
Reputation: 16235
haa is not defined in the code you have shown us. That is a compile error.
Upvotes: -1
Reputation: 2303
You forgot to declare haa = hello.getChars(0, hello_len, hello_array, 0);
Upvotes: 0