Java双向链表searchByName方法无法匹配已存在节点问题排查
双向链表searchByName方法故障修复
核心问题列表
- 空指针判断顺序错误:先访问
start节点的属性再判断start是否为空,空链表场景会直接触发空指针异常,无法正确抛出自定义的列表下溢异常 - 字符串比较逻辑错误:使用
==比较String类型内容,该运算符只能判断字符串对象的内存地址是否一致,无法判断内容是否相等,需替换为equals()方法 - 节点属性未随遍历更新:
theFirstName、theLastName仅在方法初始化时读取了首节点的属性,遍历过程中currentNode更新后没有重新读取当前节点的姓名属性,始终仅比对首节点的姓名 - 遍历终止逻辑错误:当前节点不匹配时直接输出Not found并中断循环,不会继续遍历后续节点;且尾节点无论是否匹配都会强制输出,不符合搜索逻辑
修复后代码
searchByName方法
public void searchByName(String param) throws Exception{ // 先判断链表是否为空,避免空指针 if (start == null) { throw new Exception("List Underflow"); } Node currentNode = start; param = param.toLowerCase(); boolean isFound = false; // 标记是否找到匹配项 // 输出表头 String id= "Student ID", ln="Last Name", fn="First Name", course="Course", section="Section", yl="Year Level"; System.out.format("%-10s\t%-10s\t%-10s\t%-5s\t%-10s\t%s", id, ln, fn, course, section, yl); System.out.println(); // 遍历所有节点 while(currentNode != null){ // 每次遍历都读取当前节点的姓名并转小写 String theFirstName = currentNode.firstName.toLowerCase(); String theLastName = currentNode.lastName.toLowerCase(); // 用equals比对内容 if (param.equals(theFirstName) || param.equals(theLastName)) { System.out.format("%-10s\t%-10s\t%-10s\t%-5s\t%-15s\t%d", currentNode.studentID, currentNode.lastName, currentNode.firstName, currentNode.course, currentNode.section, currentNode.yearLevel); System.out.println(); isFound = true; } currentNode = currentNode.next; } // 遍历完所有节点后判断是否找到 if (!isFound) { System.out.println("Not found"); } }
测试代码(原逻辑无需修改)
public static void main(String[] args) throws Exception { StudentRecord senators = new StudentRecord(); senators.insertEnd("110007", "Lacson", "Ping", "BSCS", "BSCS-III-A", "Active", 3); senators.insertEnd("110008", "Angara", "Sonny", "BSCS", "BSCS-III-B", "InActive", 3); senators.searchByName("Lacson"); }
修复说明
- 调整空判断顺序,优先校验链表是否为空,避免空指针异常
- 替换
==为equals()完成字符串内容比对 - 将姓名属性读取逻辑移入循环,每次遍历都读取当前节点的最新属性
- 新增匹配标记位,遍历完全部节点后再判断是否存在匹配项,避免中途中断遍历、漏查后续节点,也解决了尾节点强制输出的问题
内容的提问来源于stack exchange,提问作者Casual Engineer Zombie
相关产品推荐
相关产品推荐

