如何在数组中找到给定 int 的每个索引?

How to find every index of a given int in an array?

我试图在这个数组中找到给定索引 "max" 的每一次出现,并确认只有一个索引具有给定值最大值。

    for ( int i = 0; i < posNum; i++) {
        if ( possibilitynum[i] > max) {
            max = possibilitynum[i];
        }
    }

    if (Arrays.asList(possibilitynum).lastIndexOf(max) != Arrays.asList(possibilitynum).indexOf(max)) {
        String[] button = { possibilities[Arrays.asList(possibilitynum).indexOf(max)].substring(possibilities[Arrays.asList(possibilitynum).indexOf(max)].length()-(possibilities[Arrays.asList(possibilitynum).indexOf(max)].length()-36-(main.category.length()))), possibilities[Arrays.asList(possibilitynum).lastIndexOf(max)].substring(possibilities[Arrays.asList(possibilitynum).lastIndexOf(max)].length()-(possibilities[Arrays.asList(possibilitynum).lastIndexOf(max)].length()-36-(main.category.length())))};
        int choice=JOptionPane.showOptionDialog(null, "Two items have "+max+" of the keywords you entered! Which item is correct?", "NEED INPUT ASAP",
                JOptionPane.WARNING_MESSAGE, 0, null, button, null);

    } else {
        main.theActualLink=possibilities[Arrays.asList(possibilitynum).indexOf(max)];
    }

Max 出现多次,因此 Arrays.asList(possibilitynum).indexOf(max) 只会 return 第一个索引,而我需要所有索引。 Arrays.asList(possibilitynum).lastIndexOf(max) 只会 return 最后一个,所以我能够找到两个索引,但不是全部。提前致谢

如果我理解您的问题,那么我认为最简单的解决方案是将 count 添加到您现有的 for 循环中。像

int count = 0;
for ( int i = 0; i < posNum; i++) {
    if ( possibilitynum[i] > max) {
        max = possibilitynum[i];
        count = 1;
    } else if (possibilitynum[i] == max) {
        count++;
    }
}

编辑

如果你真的想存储索引,你可以将它们添加到 List like

List<Integer> maxIndexes = new ArrayList<>();
for ( int i = 0; i < posNum; i++) {
    if ( possibilitynum[i] > max) {
        max = possibilitynum[i];
        maxIndexes.clear();
        maxIndexes.add(i);
    } else if (possibilitynum[i] == max) {
        maxIndexes.add(i);
    }
}
int count = maxIndexes.size(); // <-- for example