如何比较java中字符串数组中的元素? [英] how to compare elements in a string array in java?

查看:30
本文介绍了如何比较java中字符串数组中的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to find duplicate words in a string array.

这是我的比较代码:

   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("
Number of words, not including duplicates: " + wordCount);

在 if 语句中,它表示 NullPointerException.这是什么意思?有一个更好的方法吗?我试着简单地做

in the if statement, it says NullPointerException. What does this mean? Is there a better way to do this? I tried simply doing

if (stringArray[i] == stringArray[j] && i!=j)

但这一直给我错误的答案.

but that kept giving me wrong answers.

推荐答案

你可以这样做以获得更好的性能:

You can do like this for beter performance:

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中字符串数组中的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆