使用 equals() 计算数组中的重复字符串

Counting duplicate strings in array with equals()

Java 的新手,我似乎无法理解:

我想要做的就是打印一个重复的字符串和它在数组中出现的次数(不使用哈希表或类似的东西,只是非常简单)。

假设这样的数组:

tempArray = {"dogs", "cats", "dogs", "dogs", "mice", "snakes", "cats"}

到目前为止,这是我的代码:

int flowerCount = 0;
for (int j = 0; j < tempArray.length - 1; j++) {
        for (int k = j + 1; k < tempArray.length; k++) {
              if( (tempArray[j].equals(tempArray[k])) && (j != k) ) {
                    System.out.println(tempArray[j]);
                    flowerCount++;
               }

         }

 }

显然这不起作用,我在这里做错了什么?这看起来应该很简单,但我无法获得正确的嵌套循环和计数器。

计算重复项的一种简单方法是尝试将它们添加到集合中。集合不允许重复,所以每次添加字符串失败,都是因为集合中已经存在该字符串

集合中的add()方法return是一个布尔值,表示添加是否成功。如果您尝试添加的字符串已经在集合中,则添加将失败并且该方法将 return false.

所以像这样:

HashSet<String> yourSet = new HashSet<>(); //Could be any kind of set, I'm just used to HashSets
int j = 0; j < tempArray.length - 1; j++) {
    if (yourSet.add(tempArray[j]) {
        //String was added succesfully, so it is not a duplicate.
    }  else {
        //String is duplicate.  Increment a duplicate counter for this string (and start at 2, if you want to include the initial occurence that is already in the set
    }
}

您可以使用 Arrays.sort 对数组进行排序。这将使相等的元素彼此相邻。然后你可以简单地用 while 循环遍历列表,寻找连续的相等元素。

int i = 0;
while (i < arr.length) {
  int start = i;
  while (i < arr.length && arr[i].equals(arr[start])) {
    ++i;
  }
  int count = i - start;
  System.out.println(arr[start] + " " + count);
}

with array and for

String printed = "";
    for(String auxOne : tempArray){
        int CountRepeat = 0;
        for(String auxTwo : tempArray){
            if(auxOne.equals(auxTwo)){
                CountRepeat++;
            }
        }
        if(CountRepeat>1 && (printed.indexOf(auxOne)==-1)){
            printed += auxOne;
            System.out.println(auxOne + " : " + CountRepeat);
        }
    }

}