【问题标题】:How to sort an array in reverse order using java?如何使用java以相反的顺序对数组进行排序?
【发布时间】:2011-04-07 16:43:53
【问题描述】:
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”类在测试类的主要方法中被拒绝。 为什么当我尝试反转数组时它会给我一个编译错误?

【问题讨论】:

  • haa 是什么?请发布您的实际代码。
  • 线程“主”java.lang.RuntimeException 中的异常:无法编译的源代码
  • 既然您显然正在学习 Java,您应该知道官方指南倾向于使用全小写的包名称。更喜欢 javalearning 而不是 javaLearning

标签: java


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我得到的错误(假设原始帖子有一些拼写错误)是Collections.reverseOrder() 返回Comparator&lt;Object&gt;

    Arrays.sort(带有比较器)只为 Object 的后代定义,因此不适用于原始类型。

    【讨论】:

      【解决方案3】:

      你忘了声明haa = hello.getChars(0, hello_len, hello_array, 0);

      【讨论】:

        【解决方案4】:

        haa 未在您向我们展示的代码中定义。那是编译错误。

        【讨论】:

        • 好的,我已经修正了代码中的错字,但它仍然给我一个错误?
        【解决方案5】:

        使用 Arrays.sort 按升序排序,然后反转数组的元素(可以通过简单的循环内联完成)。

        【讨论】:

          【解决方案6】:

          首先是代码没有遵循JAVA语言的标准。 类名应始终以大写字母开头,并且 Arrayssort() 不应将原始值列表作为参数。将 'char' 更改为 'Character' 然后使用 Arrays.sort 方法

          【讨论】:

            猜你喜欢
            • 2023-04-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2016-08-12
            • 1970-01-01
            • 1970-01-01
            • 2022-01-07
            相关资源
            最近更新 更多