如标题所示,我试图递归地返回一个 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/