我正在尝试在字符串数组中查找重复的单词。
这是我的比较代码:
for ( int j = 0 ; j < wordCount ; j++)
{
for (int i = wordCount-1 ; i > j ; i--)
{
if (stringArray[i].compareTo(stringArray[j]) == 0 && i!=j)
{
//duplicate
duplicates++;
}
}
}
wordCount -= duplicates;
System.out.print("\nNumber of words, not including duplicates: " + wordCount);
在 if 语句中,它显示 NullPointerException
。这是什么意思?有一个更好的方法吗?我尝试简单地做
if (stringArray[i] == stringArray[j] && i!=j)
但这一直给我错误的答案。
最佳答案
您可以这样做以获得更好的性能:
public int getDuplicateCount(Integer[] arr){
int count = 0;
Set<Integer> set = new HashSet<Integer>();
for (int i = 0; i < arr.length; i++) {
if (set.contains(arr[i]))
count++;
set.add(arr[i]);
}
return count;
}
关于java - java中如何比较字符串数组中的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12947254/