You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ArrayList中获取所有相同值元素的索引?

问题:无法获取ArrayList中目标元素的所有索引

当前代码仅能输出目标元素的第一个索引,例如列表为[5,5,4,5]时,查询数字5的索引会输出:

Number 5 can be found in the following indexes [0, 0, 0, 0]
期望输出为:
Number 5 can be found in the following indexes [0, 1, 3]

需求逻辑:

  • 用户输入整数添加至ArrayList,输入-1停止输入
  • 系统提示What number are you looking for?,用户输入要查询的数字
  • 输出该元素在列表中的所有索引,格式符合示例

当前代码:

import java.util.ArrayList;
import java.util.Scanner;

public class sandbox{
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int read = Integer.valueOf(reader.nextLine());
            if (read == -1) {
                break;
            }

            list.add(read);
        }
        System.out.print("What number are you looking for? ");
        int requestednumb = Integer.valueOf(reader.nextLine());
        int count = 0;

        ArrayList<Integer> index = new ArrayList<>();
        while ((list.size() > count)) {
            if (list.contains(requestednumb))
                ;
            index.add(list.indexOf(requestednumb));
            count++;
        }
        System.out.println("Number " + requestednumb + " can be found in the following indexes " + index);
    }
}

错误原因分析
  1. list.indexOf(requestednumb)方法的特性是仅返回目标元素第一次出现的索引,循环中重复调用这个方法只会不断添加同一个值
  2. 代码中if (list.contains(requestednumb));是无效代码:分号导致条件判断后没有执行任何逻辑,完全多余

修正方案

遍历列表的每个索引,检查当前索引对应的元素是否等于目标值,匹配则将当前索引加入结果列表。

修正后的完整代码(for循环版)

import java.util.ArrayList;
import java.util.Scanner;

public class sandbox{
    public static void main(String[] args) {
        Scanner reader = new Scanner(System.in);

        ArrayList<Integer> list = new ArrayList<>();
        while (true) {
            int read = Integer.valueOf(reader.nextLine());
            if (read == -1) {
                break;
            }

            list.add(read);
        }
        System.out.print("What number are you looking for? ");
        int requestednumb = Integer.valueOf(reader.nextLine());

        ArrayList<Integer> index = new ArrayList<>();
        // 遍历每个索引,检查元素是否匹配
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i) == requestednumb) {
                index.add(i);
            }
        }
        System.out.println("Number " + requestednumb + " can be found in the following indexes " + index);
    }
}

修正后的while循环版(替换原while代码块)

如果偏好使用while循环,可将原循环部分替换为:

int count = 0;
ArrayList<Integer> index = new ArrayList<>();
while (count < list.size()) {
    if (list.get(count) == requestednumb) {
        index.add(count);
    }
    count++;
}

内容的提问来源于stack exchange,提问作者Andu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 16:56:03