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

如何在不使用集合类的情况下输出ArrayList中重复元素的所有索引

Java实现查找ArrayList中目标元素的所有索引(不使用集合工具类)

原代码的问题在于使用indexOf()方法只能返回目标元素的第一个匹配索引,要获取所有重复元素的索引,我们可以通过线性遍历整个ArrayList的方式实现,完全不依赖Collections、HashMap或TreeMap这类工具类。

修改后的完整代码

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

public class IndexFinder {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        ArrayList<Integer> arrayList = new ArrayList<>();

        // 读取用户输入的整数,直到输入-1结束
        while (true) {
            int input = scanner.nextInt();
            if (input == -1) {
                break;
            }
            arrayList.add(input);
        }

        System.out.println("search for? ");
        // 读取目标数字
        int target = scanner.nextInt();
        StringBuilder result = new StringBuilder();
        result.append(target).append(" is at index ");

        // 线性遍历ArrayList,收集所有匹配的索引
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i).equals(target)) {
                if (result.length() > target.toString().length() + 12) { // 已有索引时添加分隔符
                    result.append(", ");
                }
                result.append(i);
            }
        }

        // 输出结果,处理目标不存在的情况
        if (result.toString().endsWith("index ")) {
            System.out.println(target + " is not present in the list");
        } else {
            System.out.println(result);
        }

        scanner.close();
    }
}

关键修改说明

  • 修正了原代码中错误的循环逻辑:原代码会循环读取目标,次数等于列表长度,不符合需求,改为仅读取一次目标数字
  • 用for循环逐个遍历ArrayList元素,通过get(i)获取当前元素并与目标值比较,匹配则记录索引
  • 使用StringBuilder拼接索引结果,避免多次字符串拼接的性能损耗
  • 增加了目标元素不存在时的提示逻辑

示例运行流程

  1. 用户输入:10 20 30 30 40 -1
  2. 程序提示:search for?
  3. 用户输入:30
  4. 程序输出:30 is at index 2, 3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:25:15