java - java中如何比较字符串数组中的元素?

标签 java arrays string nullpointerexception compareto

我正在尝试在字符串数组中查找重复的单词。

这是我的比较代码:

   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/

相关文章:

java - 不兼容的类型、泛型、<E>

java - 并行数组,接受多个输入

java - ListView内部布局

c - 如何更改 char* 全局?

无法获取字符串数组来复制一个随机值

java - 在 Payara 4.1 中静默回滚交易

java - Jetty 曾经用于生产部署吗?

java - 尝试在立方体表面渲染纹理

arrays - 与 AND 类似的 Postgres

Python 'pointer arithmetic' - 快速排序