Java中ArrayList搜索自定义person类元素失败问题求助
修复Java ArrayList搜索Person功能的问题
核心问题分析
你的代码存在两个致命问题导致搜索失效:
- ArrayList每次循环都会被重置为空:
ArrayList<Person> people定义在while(true)循环内部,每次执行循环都会新建空列表,之前添加的人员数据全部丢失。 - Person类未重写
equals方法:ArrayList.contains()依赖对象的equals判断相等性,默认的Object.equals()比较的是对象内存地址,而非你需要的姓名属性。
修复步骤
- 将ArrayList移到循环外部:确保列表在程序运行期间只初始化一次,持续保存添加的人员数据。
- 给Person类重写
equals和hashCode方法:让equals方法基于fName属性比较,这样contains才能正确判断姓名是否存在(重写hashCode是Java规范要求,保证和equals逻辑一致)。 - 完善退出逻辑:添加case 3的处理,实现程序正常退出。
- 优化Scanner创建:将Scanner放在循环外,避免重复创建IO资源。
修复后的完整代码
首先是完整的Person类实现:
class Person { String fName; @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); } }
然后是主类代码:
import java.util.*; public class ArrayOfPeople { public static void main(String[] args) { System.out.println("Hello"); // ArrayList移到循环外,仅初始化一次 ArrayList<Person> people = new ArrayList<>(); // Scanner放在循环外复用 Scanner scanner = new Scanner(System.in); while (true) { System.out.println("press 1 to add people"); System.out.println("press 2 to search people"); System.out.println("press 3 to exit program"); int input = scanner.nextInt(); switch (input) { case 1: System.out.println(" how many people would you like to add?"); int quantityOfNames = scanner.nextInt(); for (int i = 0; i < quantityOfNames; i++) { System.out.println(" what is the new person's first name?"); Person newPerson = new Person(); newPerson.fName = scanner.next(); people.add(newPerson); } break; case 2: System.out.println("what is the persons first name?"); String searchedName = scanner.next(); Person searchedPerson = new Person(); searchedPerson.fName = searchedName; boolean found = people.contains(searchedPerson); if (found) { System.out.println(searchedName + " IS in the system"); } else { System.out.println(searchedName + " is NOT in the system"); } break; case 3: System.out.println("Exiting program..."); scanner.close(); return; default: System.out.println("Invalid input, please enter 1, 2 or 3"); } } } }
替代方案(无需重写equals)
如果不想修改Person类,也可以通过遍历列表逐个比较姓名实现搜索:
// 替换case 2中的contains判断逻辑 boolean found = false; for (Person p : people) { if (searchedName.equals(p.fName)) { found = true; break; } }
内容的提问来源于stack exchange,提问作者scout900
相关产品推荐
相关产品推荐

