如何通过Scanner输入在ArrayList中查找对象的索引位置?
通过Scanner输入名称查找ArrayList中Detail对象的索引
背景
我有两个Java类:包含setter/getter的Detail类,以及测试类。测试类里用ArrayList存储Detail对象,代码如下:
List<Detail> details = new ArrayList<>(); details.add(new Detail("Anthony", 26)); details.add(new Detail("Thomas", 30)); details.add(new Detail("Shaun", 29)); details.add(new Detail("James", 28));
Detail类有public void setName(String name)、public void setNumber(long number)方法,同时应该有getName()方法(用于获取对象名称)。当前ArrayList输出内容为:
Name: Anthony Age: 26 Name: Thomas Age: 30 Name: Shaun Age: 29 Name: James Age: 28
问题
我想通过Scanner输入名称,找到对应Detail对象在ArrayList中的索引,但写的代码无法编译,不知道details.indexOf()该传什么参数。我的错误代码如下:
System.out.print("Type in one of the names listed above to find index of it's location: "); String name = s.nextLine(); for (Detail d : details){ if (details.contains(s.nextLine())) System.out.println("The index location of " +(scanner input/name here) " is " + details.indexOf()); }
预期效果
输入Thomas时,输出:
The index location of Thomas is 1
我知道可以用details.get(2)直接获取索引2的对象,但不知道怎么通过输入的名称反向得到索引值。请问我的思路哪里错了?
解答
你的代码存在几个关键问题:
- 重复调用Scanner输入:循环里再次调用
s.nextLine()会让程序等待新的输入,而非使用之前获取的name变量做匹配。 - contains()方法逻辑错误:
details.contains()判断的是列表中是否存在某个Detail对象,直接传字符串永远返回false。 - indexOf()参数缺失:该方法需要传入要查找的
Detail对象,你未传参数导致编译报错。
正确实现方式
方式一:遍历列表匹配名称并记录索引
用普通for循环遍历,同时记录索引,匹配到目标名称时输出结果:
Scanner s = new Scanner(System.in); System.out.print("Type in one of the names listed above to find index of it's location: "); String targetName = s.nextLine(); for (int i = 0; i < details.size(); i++) { Detail d = details.get(i); if (d.getName().equals(targetName)) { System.out.println("The index location of " + targetName + " is " + i); // 找到后跳出循环,避免无效遍历 break; } }
方式二:重写Detail的equals()方法,使用indexOf()
如果要使用indexOf()方法,需先重写Detail类的equals()(和hashCode(),遵循Java规范),让它根据名称判断对象相等性:
// 在Detail类中添加以下代码 @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Detail detail = (Detail) o; return Objects.equals(name, detail.name); } @Override public int hashCode() { return Objects.hash(name); }
然后在测试类中,创建临时Detail对象(仅设置目标名称),用indexOf()查找:
Scanner s = new Scanner(System.in); System.out.print("Type in one of the names listed above to find index of it's location: "); String targetName = s.nextLine(); Detail tempDetail = new Detail(targetName, 0); // 年龄不影响,equals只判断名称 int index = details.indexOf(tempDetail); if (index != -1) { System.out.println("The index location of " + targetName + " is " + index); } else { System.out.println("Name not found"); }
注意事项
- 必须确保
Detail类有getName()方法,否则无法获取对象名称进行匹配。 - 如果需要忽略名称大小写,可以用
equalsIgnoreCase()替代equals()做匹配。
内容的提问来源于stack exchange,提问作者Donpublo
相关产品推荐
相关产品推荐

