Removing duplicate strings from an array?

前端 未结 9 753
野的像风
野的像风 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:23

    1) I think you need to use the equals operator. Try

    if (!wordList[i].equals(wordList[j])){
    

    instead of !=.

    2) Also Kevin is right. You need to set t back to false.

    3) Side note as pointed out by others already: To be more efficient you should start the inner loop with

    for (j = i+1; j < wordList.length; j++) {
    

    4) Another side note: Your result array is still too long. If you don't want to use a List and it is ok to loose the original array you could go with a solution as suggested by Zim-Zam O'Pootertoot and set the original duplicates to null, add a counter to count how many null values you assigned, initialize the new array with the correct size and loop a final time over the first array and copy only the non-null values into your new array.

提交回复
热议问题