How do I put only unique values into an array?

我怕爱的太早我们不能终老 提交于 2019-12-06 08:47:36
djechlin

Use Set. Array is the wrong data type for this problem.

It contains a .toArray() method that will give you back an array after you've constructed the set, if that is what you require.

Use a Set. Starting from your code:

HashSet<String> noDuplicate = new HashSet<String>();
for(int i=0;i<strings.length;i++)
{
  for(int a=0;a<strings2.length;a++)
  {
    if(strings[i].equals(strings2[a]))
    {
      noDuplicate.add(strings[i]);
    }
  }
}

// And then if you need an array:
String[] noDupArray = new String[noDuplicate.size()];
noDuplicate.toArray(noDupArray);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!