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

ArrayList中按ID查询指定Payment对象无返回结果的问题排查

排查getPayment()方法无返回结果的问题

让我来帮你定位这个问题,你调用r.getPayment(333)后没拿到预期的支付对象,大概率是以下几个环节出了问题,咱们一步步排查:

1. 先确认Payment类的核心实现是否正确

你创建Payment对象时传入的第二个参数是支付ID(比如333、9000),但如果Payment类的构造方法没把这个参数赋值给成员变量,或者getPaymentId()方法没正确返回这个值,那遍历集合时肯定匹配不上。

你的Payment类必须包含类似这样的代码:

public class Payment {
    // 成员变量
    private String paymentType;
    private int paymentId;
    private double price;
    private Date paymentDate;
    private String description;

    // 构造方法必须正确接收并赋值参数
    public Payment(String paymentType, int paymentId, double price, Date paymentDate, String description) {
        this.paymentType = paymentType;
        this.paymentId = paymentId; // 关键:这里必须把传入的ID赋值给成员变量
        this.price = price;
        this.paymentDate = paymentDate;
        this.description = description;
    }

    // getPaymentId()必须正确返回成员变量的值
    public int getPaymentId() {
        return paymentId;
    }

    // 其他属性的getter方法
    public String getPaymentType() { return paymentType; }
    public double getPrice() { return price; }
    public Date getPaymentDate() { return paymentDate; }
    public String getDescription() { return description; }
}

如果构造方法里漏了给paymentId赋值,或者getPaymentId()返回的是其他值,那getPayment()方法里的条件判断永远不会成立。

2. 检查你是否正确处理了getPayment()的返回结果

你当前的代码只是调用了r.getPayment(333),但没有输出或使用返回的对象。比如你需要添加代码来查看结果:

// 调用方法并接收返回值
Payment foundPayment = r.getPayment(333);
if (foundPayment != null) {
    System.out.println("找到匹配的支付记录:");
    System.out.println("支付类型:" + foundPayment.getPaymentType());
    System.out.println("支付ID:" + foundPayment.getPaymentId());
    System.out.println("支付金额:" + foundPayment.getPrice());
    System.out.println("支付描述:" + foundPayment.getDescription());
    System.out.println("支付日期:" + foundPayment.getPaymentDate());
} else {
    System.out.println("未找到ID为333的支付记录");
}

如果只是调用方法但不输出,你会误以为没返回结果,但实际上方法可能已经返回了对象,只是你没查看。

3. 临时添加调试日志,确认遍历过程

你可以在Invoice类的getPayment()方法里加打印语句,看看遍历集合时的具体情况:

public Payment getPayment(int paymentId) {
    for (Payment temp: payments) {
        // 临时打印,查看当前遍历到的ID
        System.out.println("正在检查支付ID:" + temp.getPaymentId());
        if (temp.getPaymentId() == paymentId) {
            System.out.println("找到匹配的ID:" + paymentId);
            return temp;
        }
    }
    System.out.println("遍历结束,未找到ID:" + paymentId);
    return null;
}

通过这些日志,你能清楚看到:集合里的支付ID是什么、有没有匹配到目标ID,从而快速定位问题。

额外验证:检查addpayment方法的打印结果

你的addpayment方法会在添加后打印所有支付记录,你可以仔细核对打印出的payment id是不是333和9000。如果打印的ID和你传入的不一致,说明Payment构造方法的参数顺序可能写错了(比如把ID参数放到了其他位置)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:27:49