如何解决Java中的NullPointerException? [英] How to work around a NullPointerException in Java?
问题描述
所以我有一个文本文件,其中包含导入到程序中的一串字符串,程序要做的是寻找第一个重复字符串的第一个索引:
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;
问题是我收到此错误:
这是一个 NullPointerException
,据我了解,这意味着我的字符串数组中基本上有一个null值.有什么简单的解决方案,我错过了吗?可能改写我的方法?
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?
推荐答案
假设您的诊断正确无误
...这意味着我的字符串数组中基本上有一个null值...
... it means that there's basically a null value(s) in my array of strings ...
...我可以想到两种解决方法.
... I can think of two workarounds.
-
摆脱数组中的
null
引用.完全删除它们,或将其替换为(例如)"
或"null"
或其他无害的东西.
Get rid of the
null
references in the array. Remove them entirely, or replace them with (say)""
or"null"
or something else harmless.
Arrays.sort
方法的重载带有第二个参数: Comparator
.因此,您可以做的是实现一个 Comparator
,该处理器可以处理 null
而不会抛出NPE.(例如,它可以将 null
视为小于所有非null字符串.)
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.)
以下是处理 null
的示例比较器:
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);
}
}
}
或者,对于Java 8和更高版本,您可以按以下方式构建一个:
Alternatively, for Java 8 and later you can build one as follows:
Comparator.nullsFirst(Comparator.naturalOrder())
这篇关于如何解决Java中的NullPointerException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!