如何在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); } }
错误原因分析
list.indexOf(requestednumb)方法的特性是仅返回目标元素第一次出现的索引,循环中重复调用这个方法只会不断添加同一个值- 代码中
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
相关产品推荐
相关产品推荐

