
本文详解如何在 ArrayList 中准确查找指定姓名,解决因未重写 equals() 导致 contains() 失效的问题,并提供手动遍历与重写 equals/hashCode 两种专业方案。
本文详解如何在 arraylist
在 Java 中,使用 ArrayList.contains() 搜索自定义类(如 Person)对象时,默认调用的是 Object.equals() 方法——它仅比较对象引用是否相同,而非内容是否相等。因此,即使两个 Person 对象的 fName 字段值完全一致,contains() 仍会返回 false,这正是你遇到“始终提示未找到”的根本原因。
✅ 推荐方案一:手动遍历 + 字符串精确匹配(适合初学者)
最直观、可控性强的方式是显式遍历列表,逐个比较目标字段:
// 假设 Person 类中 fName 是 public String 字段(实际建议使用 getter)
String searchedName = scanner.next();
boolean found = false;
for (Person p : people) {
if (p.fName != null && p.fName.equals(searchedName)) {
found = true;
break;
}
}
if (found) {
System.out.println(searchedName + " IS in the system");
} else {
System.out.println(searchedName + " is NOT in the system");
}⚠️ 注意事项:
- 必须判空(
p.fName != null),避免NullPointerException;equals()区分大小写;如需忽略大小写,改用p.fName.equalsIgnoreCase(searchedName);- 若
fName是私有字段,请在Person类中添加公共 getter 方法(如getFirstName()),并改为p.getFirstName().equals(...)。
✅ 推荐方案二:重写 equals() 和 hashCode()(面向对象最佳实践)
若希望 contains()、remove()、HashSet 等集合操作均能按业务逻辑工作,应在 Person 类中正确重写 equals() 与 hashCode():
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。
立即学习“Java免费学习笔记(深入)”;
public class Person {
private String fName; // 建议使用 private + getter/setter
// 构造方法、getter、setter 略...
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(fName, person.fName);
}
@Override
public int hashCode() {
return Objects.hash(fName);
}
}重写后,people.contains(new Person("Alice")) 将真正基于姓名内容判断,而不仅依赖引用。
? 其他关键改进点(修复原代码缺陷)
-
ArrayList初始化位置错误:原代码中ArrayList<person> people = new ArrayList();</person>写在while(true)循环内,导致每次菜单操作都会清空列表。应移至循环外,确保数据持久存在。 -
类名规范:Java 约定类名首字母大写 →
Person而非person;变量名小驼峰 →fName建议改为firstName并封装为私有字段。 -
资源管理:
Scanner应在程序退出前关闭(scanner.close()),避免资源泄漏。
✅ 完整可运行示例片段(修正版核心逻辑)
ArrayList<Person> people = new ArrayList<>(); // ✅ 移出循环!
Scanner scanner = new Scanner(System.in);
// ... 菜单逻辑中 case 2:
System.out.print("What is the person's first name? ");
String searchedName = scanner.next().trim(); // 去除首尾空格
boolean found = false;
for (Person p : people) {
if (p.getFirstName() != null && p.getFirstName().equalsIgnoreCase(searchedName)) {
found = true;
break;
}
}
System.out.println(found ?
searchedName + " IS in the system" :
searchedName + " is NOT in the system");掌握这两种方式,你不仅能解决当前作业问题,更将建立起对 Java 对象比较机制和集合行为的深层理解——这是编写健壮、可维护面向对象程序的关键基础。

















