java 使用空值对数组进行排序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14514467/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 16:30:47  来源:igfitidea点击:

Sorting array with null values

javaarrays

提问by jl90

I have a program that allows user to delete an element from an array and I am trying to sort them in alphabetic order using compareTo(); through a for loop. However, the null values are giving me problems. For example an array with null values:

我有一个程序允许用户从数组中删除一个元素,我正在尝试使用 compareTo() 按字母顺序对它们进行排序;通过 for 循环。但是,空值给我带来了问题。例如具有空值的数组:

String[] myArray = {"Apple", "Banana", null, "Durian", null, null, "Grapes"};

When Java is comparing them and reads a null value, it would give me a NullPointerException.

当 Java 比较它们并读取空值时,它会给我一个 NullPointerException。

Is there any way that I can sort this array with null values at the back? For example:

有什么办法可以在后面用空值对这个数组进行排序吗?例如:

{"Apple", "Banana", "Durian", "Grapes", null, null, null}

I know that using Vectors can solve the problem but I am just curious if there is any way that I can just do it without changing my array to vectors.

我知道使用 Vectors 可以解决问题,但我很好奇是否有任何方法可以在不将数组更改为向量的情况下做到这一点。

回答by Evgeniy Dorofeev

try this

试试这个

    Arrays.sort(myArray, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            if (o1 == null && o2 == null) {
                return 0;
            }
            if (o1 == null) {
                return 1;
            }
            if (o2 == null) {
                return -1;
            }
            return o1.compareTo(o2);
        }});

it produces the required order

它产生所需的订单

回答by AlexWien

write your own Comparatorthat accepts null values, and pass that comparator to the Arrays.sort() method

编写自己的Comparator接受空值的方法,并将该比较器传递给Arrays.sort() 方法