2011-04-07 70 views
4
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()); 
} 

「myarray」類在測試類的主要方法中被定義爲defiend。 爲什麼當我嘗試顛倒數組時,會給我一個編譯錯誤?如何使用java以相反的順序對數組進行排序?

+1

什麼是錯誤信息? – 2011-04-07 16:44:17

+2

什麼是'haa'?請發佈您的*實際*代碼。 – 2011-04-07 16:45:40

+0

線程「main」中的異常java.lang.RuntimeException:不可編譯的源代碼 – Aaron 2011-04-07 16:47:21

回答

6

Collections.reverseOrder()返回Comparator<Object>。而Arrays.sort用比較不適合原語

工作這應該工作

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());        
    } 
} 
0

你忘了申報haa = hello.getChars(0, hello_len, hello_array, 0);

0

HAA是不是在你對我們的代碼中定義。這是一個編譯錯誤。

+0

好的,我已經修復了代碼中的錯字,它仍然給我一個錯誤? – Aaron 2011-04-07 16:52:09

2

我得到的錯誤(假設原來的文章有一些錯別字)是Collections.reverseOrder()返回Comparator<Object>

Arrays.sort(帶分隔符)僅爲Object的後代定義,因此不適用於基元類型。

0

使用Arrays.sort升序排序,然後反轉數組的元素(可以用一個簡單的循環,內聯方式完成)。

0

首先是代碼沒有遵循JAVA語言的標準。 類名應始終以UPPER大小寫開始,並且排序()數組不應將值的原始值列表作爲參數。將'char'改爲'Character',然後使用Arrays.sort方法

相關問題