1

I have a String array of size 1000:

String[] subStrStore = new String[1000];

I have only 6 elements in the array. If I sort it using:

Arrays.sort(subStrStore);

I am getting a null pointer exception because it tries to compare null elements. How can solve this problem?

Boann
  • 48,794
  • 16
  • 117
  • 146
  • 3
    have a list and trim that to size, or use ordered collections. – Stultuske Jan 21 '16 at 09:08
  • 4
    you could write your own comparator which handles null values and use sort version with comparator (https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28T[],%20java.util.Comparator%29), or if the entries that are non null are in a block you can use sort with start and end index (https://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#sort%28float[],%20int,%20int%29 ) – Kai Iskratsch Jan 21 '16 at 09:16
  • 1
    While possibly not avoiding of fixing your problem, you should consider Lists or other collections over Arrays http://stackoverflow.com/a/1589952/360211 – weston Jan 21 '16 at 09:49

5 Answers5

4

If the strings are the first 6 elements you can use

Arrays.sort(subStrStore, 0, 6);
Thomas Kläger
  • 17,754
  • 3
  • 23
  • 34
3

Use custom comparator,

Arrays.sort(subStrStore, new Comparator<String>() {

            @Override
            public int compare(String o1, String o2) {
                if (o1 == o2)
                    return 0;

                if (o1 == null) {
                    return -1;
                }
                if (o2 == null) {
                    return 1;
                }

                return o1.compareTo(o2);

            }
        });

this should push all your nulls at the end of your array

user902383
  • 8,420
  • 8
  • 43
  • 63
1

Remove the null elements and sort.

    String[] subStrStore = new String[1000];
    subStrStore[10] = "f";
    subStrStore[200] = "e";
    subStrStore[300] = "d";
    subStrStore[500] = "c";
    subStrStore[750] = "b";
    subStrStore[900] = "a";
    String[] sorted = Stream.of(subStrStore)
        .filter(s -> s != null)
        .sorted()
        .toArray(String[]::new);
    System.out.println(Arrays.toString(sorted));
    // -> [a, b, c, d, e, f]
0

Have a look at Arrays.copyOf() from java.util.Arrays. It will do the job I believe .

asb
  • 11
  • 2
-2

I think the best way is to check element before compare. something like that:

if(object == null){break;}

THIS WILL WORK ONLY IF U USE FIRST ELEMENTS OF ARRAY. 1, 2, 3, 4 NULL, NULL ... x1000. NOT 1,2, NULL, NULL, 3, 4, 5. <- IF THAT WAY U HAVE TO USE EXCEPTIONS :) you dont want check other elements after first null, or you can use just try catch and handle the exception.

grzeniuk
  • 1
  • 2
  • 1
    Don't use exceptions as [normal control flow](http://stackoverflow.com/a/1546525/360211). – weston Jan 21 '16 at 09:52