与空值数组排序 [英] Sorting array with null values

查看:139
本文介绍了与空值数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,允许用户从一个数组中删除一个元素,我想使用的compareTo()按字母顺序排序他们;通过一个for循环。但是,空值是给我的问题。例如空值的数组:

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:

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

在Java是比较它们并读取空值,它会给我一个NullPointerException异常。

When Java is comparing them and reads a null value, it would give me a 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.

推荐答案

试试这个

    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

这篇关于与空值数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆