How to work around a NullPointerException in Java?

2019-07-30 19:21发布

So I have a text file that contains a bunch of strings that I import into the program and what my program does is look for the first index of the first duplicate string:

static final int NOT_FOUND = -1;
dupeIndex = indexOfFirstDupe( wordList, wordCount );
    if ( dupeIndex == NOT_FOUND )
        System.out.format("No duplicate values found in wordList\n");
    else
        System.out.format("First duplicate value in wordList found at index %d\n",dupeIndex);

and the method I use to find the first index of the duplicate is as follows:

static int indexOfFirstDupe( String[] arr, int count )
{       

    Arrays.sort(arr);
    int size = arr.length;
    int index = NOT_FOUND;

    for (int x = 0; x < size; x++) {
        for (int y = x + 1; y < size; y++) {
            if (arr[x].equals(arr[y])) {
                index = x;
                break;
            }
        }
    }
    return index;

The problem is that I get this error:

enter image description here

It's a NullPointerException and from my understanding it means that there's basically a null value(s) in my array of strings(?). Is there any simple solution to this that I am missing? Possibly rewording my method?

3条回答
冷血范
2楼-- · 2019-07-30 19:40

There is a better way to do what you want to do. This is complexity O(n) vs yours is O(n^2) + failing sort.

  public int indexOfFirstDup(String[] arr) {
    Set<String> valuesFound = new HashSet<>();
    for (int i=0;i<arr.length; i++) {
      String s = arr[i];
      // ignore nulls
      if (s == null) { continue; }
      if (valuesFound.contains(s)) {
        // here we identified a duplication and we can leave 
        return i;
      } else {
        valuesFound.add(s);
      }
    }
    // no dups
    return -1;
   }

NOTE the code has not been compiled nor tested - its just an idea!

查看更多
迷人小祖宗
3楼-- · 2019-07-30 19:52

Assuming that you are correct in your diagnosis

... it means that there's basically a null value(s) in my array of strings ...

... I can think of two workarounds.

  1. Get rid of the null references in the array. Remove them entirely, or replace them with (say) "" or "null" or something else harmless.

  2. There is an overload of the Arrays.sort method that takes a second argument: a Comparator. So what you could do is to implement a Comparator that can handle null without throwing an NPE. (For example, it could treat null as smaller than all non-null strings.)

Here's an example comparator that deals with null:

    public class NullSafeStringComparator implements Comparator<String> {
        public int compare(String s1, String s2) {
            if (s1 == s2) {
                return 0;
            } else if (s1 == null) {
                return -1;
            } else if (s2 == null) {
                return 1;
            } else {
                return s1.compareTo(s2);
            }
        }
    }

Alternatively, for Java 8 and later you can build one as follows:

    Comparator.nullsFirst(Comparator.naturalOrder())            
查看更多
唯我独甜
4楼-- · 2019-07-30 19:55

The error is caused by Array.sort(arr);

According to Java doc (https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#sort-java.lang.Object%3aA-):

Sorts the specified array of objects into ascending order, according to the natural ordering of its elements. All elements in the array must implement the Comparable interface.

It is very likely that the exception was thrown when the sort tries to call the compareTo method on the null objects of the String array.

So one simple direct solution is to make sure no null objects in your String array...

查看更多
登录 后发表回答