java - 递归返回特定索引的arrayList

标签 java recursion arraylist

如标题所示,我试图递归地返回一个 gpa 高于 3.5 的 Student 对象数组列表。这是我的尝试。

public static ArrayList<Student> honorsStudents(Student[] list, int n) {
    ArrayList<Student> studentsList = new ArrayList<Student>();
    if (n == 0) {
        return studentsList;
    } else {
        boolean currentIsHonors = list[n - 1].isHonors();
        if (currentIsHonors) {
            studentsList.add(list[n - 1]);
            return honorsStudents(list, n - 1);
        } else {
            return honorsStudents(list, n - 1);
        }
    }
}

isHonors()当然是判断gpa是否大于3.5。 不确定我到底在哪里搞砸了。

我的方法没有返回空 arrayList。不捕获 GPA 大于 3.5 的任何索引。

有什么想法吗?谢谢

最佳答案

您正在每个方法迭代中创建一个新的 ArrayList。这永远不会以递归方式工作,因为您需要将元素添加到相同列表。

考虑使用一个使用空白列表开始递归的基本方法,然后为递归的每次迭代传递该相同列表:

//This method takes in the initial values and starts the actual recursion
public static ArrayList<Student> honorsStudents(Student[] list, int n)
{
    return honorStudents(list, n, new ArrayList<Student>());
}

//this is the actual recursive method
public static ArrayList<Student> honorsStudents(Student[] list, int n, List<Student> studentsList)
{
    if (n==0)
    {
        return studentsList;
    }       
    else
    {
        boolean currentIsHonors = list[n-1].isHonors();
        if(currentIsHonors)
        {
            studentsList.add(list[n-1]);
            return honorsStudents(list, n-1, studentsList);
        }
        else 
        {
            return honorsStudents(list, n-1, studentsList);
        }
    }
}

关于java - 递归返回特定索引的arrayList,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29083844/

相关文章:

java - Android - 强制搜索 View 以编程方式打开

python - 为什么第8行递归代码的参数是 'string[:i] + string[i + 1:]'而不是 'string'

java - 使用返回的 ArrayList

c++ - 递归地在 double 数组中找到负数

java - BSTSet 使用递归实现方法 contains(T value) 和 add(T value)

java - 在 Java 中使用 List 和 LinkedHashSet 从字符串中删除重复值后如何获取 Arraylist<String>

java - 从另一个类添加到 ArrayList

java - super 录音机不写入文件

java - tomcat下创建文件

java - 在 Java 中,写入文件比迭代数组慢多少?