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:
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?
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.
NOTE the code has not been compiled nor tested - its just an idea!
Assuming that you are correct in your diagnosis
... I can think of two workarounds.
Get rid of the
null
references in the array. Remove them entirely, or replace them with (say)""
or"null"
or something else harmless.There is an overload of the
Arrays.sort
method that takes a second argument: aComparator
. So what you could do is to implement aComparator
that can handlenull
without throwing an NPE. (For example, it could treatnull
as smaller than all non-null strings.)Here's an example comparator that deals with
null
:Alternatively, for Java 8 and later you can build one as follows:
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...