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?

3

5 Answers 5

4

If the strings are the first 6 elements you can use

Arrays.sort(subStrStore, 0, 6);
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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]

Comments

0

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

Comments

-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.

1 Comment

Don't use exceptions as normal control flow.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.