Removing duplicate strings from an array?

前端 未结 9 741
野的像风
野的像风 2021-01-24 06:54

How can I remove duplicate strings from a string array without using a HashSet?

I try to use loops, but the words not delete.

StringBuffer outString = ne         


        
相关标签:
9条回答
  • 2021-01-24 07:39

    How about using a List:

    wordList = outString.toString().split(", ");
    List<String> finalList = new ArrayList<String>();
    for(String val : wordList) {
      if(!finalList.contains(val)) {
        finalList.add(val);
      }
    }
    

    A Set would be more efficient, however. If you can't use a List or a Set, and you are forced to remove the duplicates, then you will have to loop through the array each time, which will perform horribly.

    0 讨论(0)
  • 2021-01-24 07:44

    You probably want to set t back to false after pulling the value you want:

    if(t)
    {
         wordList1[i]=wordList[i];
         t = false;
    }
    

    Also this:

    if((wordList[i]!=wordList[j])&&(j>i))
    

    Will always return true since strings are immutable (unless you compared a string to an exact reference of itself which you disallow with j>i). You need to change it to say this:

    if (!(wordList[i].equals(wordList[j]))&&(j>i))
    

    Using .equals will compared that they contain the same string, not that they point to the exact reference of a string.

    Not sure if that's the only problems or not, a bit unclear from what's given.

    0 讨论(0)
  • 2021-01-24 07:45

    If you are allowed to use Lists, you can define a generic method that does this fairly easily:

    public <T> T[] removeDuplicates(final T[] array) {
        List<T> noDuplicates = new ArrayList<T>();
        for (T arrayElem : array) {
            if (!noDuplicates.contains(arrayElem)) {
                noDuplicates.add(arrayElem);
            }
        }
        return (T[]) noDuplicates.toArray();
    }
    
    0 讨论(0)
提交回复
热议问题