You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java OOP/ADT学生管理系统删除功能故障排查求助

问题分析与解决方案:学生收藏系统删除功能异常

错误原因分析

  1. 未重写equals()方法导致对象匹配失败
    User类及其子类Candidate、Admin没有重写Object类的equals()方法,默认使用引用地址比较。删除时新创建的Candidate对象,哪怕ID、姓名和列表中的完全一致,也是不同的对象实例,equals()会返回false,直接导致remove()和contains()无法匹配到目标对象。

  2. SortedArrayList.remove()方法存在数组越界风险
    在remove()方法中,循环结束后直接访问array[index],如果目标对象不存在,index会等于numberOfEntries,此时array[index]会触发ArrayIndexOutOfBoundsException。

  3. SortedArrayList.get()方法下标逻辑错误
    get()方法直接用传入的givenPosition作为数组下标,但用户输入的通常是从1开始的位置,而数组下标从0开始,会导致下标越界异常。

解决方案

1. 重写User类的equals()和hashCode()方法

以ID作为唯一标识判断对象相等,修改User类:

package entity;

public class User implements Comparable<User> {
    private int id;
    private String name;

    // 原有构造方法、getter/setter、compareTo方法保持不变

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return id == user.id;
    }

    @Override
    public int hashCode() {
        return Integer.hashCode(id);
    }
}

2. 修复SortedArrayList.remove()的越界问题

增加下标合法性判断,修改remove()方法:

@Override
public boolean remove(T anEntry) {
    if (numberOfEntries == 0) {
        return false;
    }
    int index = 0;
    while (index < numberOfEntries && array[index].compareTo(anEntry) < 0) {
        index++;
    }
    // 先判断下标是否在有效范围内,再执行匹配
    if (index < numberOfEntries && array[index].equals(anEntry)) {
        removeGap(index + 1);
        numberOfEntries--;
        return true;
    }
    return false;
}

3. 修复SortedArrayList.get()的下标转换问题

将用户输入的1起始位置转为0起始的数组下标:

@Override
public T get(int givenPosition) {
    if (givenPosition < 1 || givenPosition > numberOfEntries) {
        throw new IndexOutOfBoundsException("Invalid position: " + givenPosition);
    }
    T result = array[givenPosition - 1];
    return result;
}

4. 简化删除功能(可选)

既然ID是唯一标识,删除时只需输入ID即可,无需姓名:

public void deleteStudent() {
    System.out.println("Enter candidate ID:");
    int adminId = input.nextInt();
    input.nextLine(); // 消耗换行符

    Candidate candidateToDelete = new Candidate(adminId);
    boolean success = stuList.remove(candidateToDelete);

    if (success) {
        System.out.println("Candidate removed successfully.");
    } else {
        System.out.println("Candidate not found.");
    }
}

内容的提问来源于stack exchange,提问作者Alvin Luke

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 15:35:19