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

Java递归方法返回空列表问题:递归填充后仍返回空集合

解决递归填充ArrayList返回空列表的问题

我帮你分析下这个问题哈!你遇到的递归返回空列表的情况,核心原因是递归调用时没有把下层返回的列表元素合并到当前层的列表中——每次递归都会新建独立的daysList,当递归到目标分支填充完列表后,它的结果没有传递回上层调用,最终最外层返回的还是初始的空列表。

问题根源拆解

假设你的代码逻辑大致是这样(补全你未写完的部分):

private static List<WebElement> checkMonth(WebDriver driver) {
    List<WebElement> months = driver.findElements(By.xpath("//div[@class='DayPicker-Caption']"));
    List<WebElement> daysList = new ArrayList<>();
    
    // 判断是否为目标月份,否则切换月份后递归
    if (!isTargetMonth(months.get(0).getText())) {
        driver.findElement(By.xpath("你的下一页按钮XPath")).click();
        checkMonth(driver); // 这里只调用了递归,但没接收/合并返回的结果!
    } else {
        daysList = driver.findElements(By.xpath("日期元素XPath"));
    }
    return daysList;
}

当递归进入目标月份分支时,该层级的daysList确实被填充了,但它返回给上一层后,上一层并没有把这些元素添加到自己的daysList里,所以上层的daysList还是空的,最终返回到最外层的就是初始创建的空列表。

两种可行的解决方案

方案1:合并递归返回的列表元素

在递归调用后,把返回的列表元素添加到当前层的daysList中,确保结果能逐层传递回去:

private static List<WebElement> checkMonth(WebDriver driver) {
    List<WebElement> months = driver.findElements(By.xpath("//div[@class='DayPicker-Caption']"));
    List<WebElement> daysList = new ArrayList<>();
    
    String currentMonth = months.get(0).getText();
    // 替换成你判断目标月份的逻辑
    if (!"2024年6月".equals(currentMonth)) {
        // 点击下一页切换月份
        driver.findElement(By.xpath("//button[@class='DayPicker-NavButton--next']")).click();
        // 关键:把递归返回的列表元素合并到当前列表
        daysList.addAll(checkMonth(driver));
    } else {
        // 填充目标月份的所有日期元素
        daysList.addAll(driver.findElements(By.xpath("//div[@class='DayPicker-Day']")));
    }
    
    return daysList;
}

方案2:重载方法,传递共享列表(更高效)

通过重载方法,让递归过程共用同一个列表,避免多次创建和合并列表的开销:

// 对外暴露的初始化方法,创建列表并启动递归
public static List<WebElement> getTargetMonthDays(WebDriver driver) {
    List<WebElement> daysList = new ArrayList<>();
    checkMonth(driver, daysList);
    return daysList;
}

// 递归核心方法,接收已有的列表进行填充
private static void checkMonth(WebDriver driver, List<WebElement> daysList) {
    List<WebElement> months = driver.findElements(By.xpath("//div[@class='DayPicker-Caption']"));
    String currentMonth = months.get(0).getText();
    
    if (!"2024年6月".equals(currentMonth)) {
        driver.findElement(By.xpath("//button[@class='DayPicker-NavButton--next']")).click();
        // 递归调用,继续往同一个列表里添加元素
        checkMonth(driver, daysList);
    } else {
        // 将目标月份的日期元素添加到共享列表中
        daysList.addAll(driver.findElements(By.xpath("//div[@class='DayPicker-Day']")));
    }
}

这两种方案都能解决你遇到的问题,确保递归填充的元素能正确传递并返回给调用方。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 04:22:18