Java Course列表ID重复校验方法失效问题排查及解决求助
现有代码核心问题
- 校验逻辑不完整:当前
ifExist方法仅会校验新输入的ID是否与本次触发重复的单条Course记录ID不同,没有重新遍历整个列表校验新ID是否和其他已有记录重复。比如第三次新增时输入ID=2触发重复,修改为ID=1时,仅判断1≠2就通过校验,完全没检查列表里已经存在ID=1的记录,这是导致重复ID入库的核心原因。 - 输入流残留换行符未处理:你在
addCourse中调用input.nextInt()读取ID后,没有消费输入缓冲区中残留的换行符,后续ifExist中调用input.nextLine()会直接读取到空字符串,这就是运行时输入一次重复ID会弹出好几次提示的原因。 - 迭代器使用逻辑错误:迭代器是单向遍历的,遍历过一次后就无法回到列表头部,你修改ID后不会重新遍历整个列表做全量校验,逻辑没有形成闭环。
- 代码笔误:一是
addCourse方法参数是courselist,但调用ifExist时传的是booklist,如果没有全局定义booklist变量本身就是错误;二是course.setPersonDd(personid)是拼写错误,应为setPersonID。
修复方案
方案1:最小改动修复原有逻辑
直接修改ifExist方法,每次获取新ID后都做全量校验,不需要传入迭代器参数:
public static int ifExist(List<Course> courselist, int inputId) { Scanner input = new Scanner(System.in); boolean isDuplicate = true; int finalId = inputId; String digitRegex = "\\d{1,10000}"; // 外层循环:直到找到不重复的ID才退出 while (isDuplicate) { isDuplicate = false; // 全量遍历列表判断ID是否重复 for (Course course : courselist) { if (course.getPersonID() == finalId) { isDuplicate = true; break; } } if (isDuplicate) { System.out.print("No duplicate number is accepted. Please enter another number: "); boolean flag = false; String value = null; do { value = input.nextLine(); flag = value.matches(digitRegex); if (!flag) System.out.print("Please enter a number only!: "); } while (!flag); finalId = Integer.parseInt(value); } } return finalId; }
对应修改addCourse的调用逻辑:
System.out.print("\nEnter the person ID: "); personid = input.nextInt(); input.nextLine(); // 吃掉nextInt残留的换行符 personid = ifExist(courselist, personid); // 删除原有迭代器创建逻辑即可
方案2:优化性能(推荐)
维护一个全局的HashSet<Integer> existIdSet,每次新增ID时直接调用existIdSet.contains(id)判断重复,时间复杂度从O(n)降到O(1),适合列表数据量大的场景:
- 每次新增Course成功时,把personid存入set
- 每次校验时直接判断set中是否存在该ID即可
- 如果需要支持删除操作,删除Course时同步把ID从set中移除即可
内容的提问来源于stack exchange,提问作者undernameray
相关产品推荐
相关产品推荐

