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

如何获取ArrayList中匹配指定年份的全部Cars对象索引

如何返回所有匹配年份的Cars对象索引

嗨,这个问题很好解决~你当前的代码找到第一个匹配项就直接return了,所以只能拿到第一个索引。要返回所有符合条件的索引,我们需要把这些索引收集起来,而不是中途终止遍历。

修改核心思路:

  • 把方法返回类型从int改成List<Integer>,这样能容纳多个索引值
  • 遍历过程中,每找到一个匹配年份的Cars对象,就把对应的索引添加到列表中
  • 遍历完成后返回这个列表(如果没有匹配项,列表会是空的,调用方可以通过isEmpty()轻松判断结果)

基础版修改代码:

import java.util.ArrayList;
import java.util.List;

public static List<Integer> searchYear(ArrayList<Cars> cars, int key) {
    // 创建列表存储所有匹配的索引
    List<Integer> matchingIndices = new ArrayList<>();
    int size = cars.size();
    
    for (int i = 0; i < size; i++) {
        Cars currentCar = cars.get(i);
        if (currentCar.getYear() == key) {
            // 符合条件就添加索引,不直接返回
            matchingIndices.add(i);
        }
    }
    
    return matchingIndices;
}

Java 8+ 流API简化版:

如果你的项目使用Java 8及以上版本,还可以用流API简化代码,写法更简洁:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public static List<Integer> searchYear(ArrayList<Cars> cars, int key) {
    return IntStream.range(0, cars.size())
            // 过滤出年份匹配的索引
            .filter(i -> cars.get(i).getYear() == key)
            // 将int类型索引装箱为Integer
            .boxed()
            // 收集为List返回
            .collect(Collectors.toList());
}

调用示例:

拿到返回的列表后,你可以这样使用:

ArrayList<Cars> myCars = new ArrayList<>();
// 假设已向myCars中添加Cars实例
List<Integer> year2014Indices = searchYear(myCars, 2014);

if (!year2014Indices.isEmpty()) {
    System.out.println("所有2014年车辆的索引:" + year2014Indices);
} else {
    System.out.println("未找到生产年份为2014年的车辆");
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:42:46