20

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"};

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.

1
  • 4
    With Guava, this is straightforward: Arrays.sort(array, Ordering.natural().nullsLast()) Commented Jan 25, 2013 at 3:22

2 Answers 2

28

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

Sign up to request clarification or add additional context in comments.

Comments

7

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.