[英]The reverse method should print out lst in reverse. It prints an empty arrayList instead. Why is this happening and how do I fix it?
This is the class with the buildList method which builds the in这是带有 buildList 方法的 class
class Recursive
{
public static ArrayList<Integer> reversedList = new ArrayList<Integer>();
public static ArrayList<Integer> buildList(int n)//builds the arrayList based on integer. If the int is 5 then the contents are 1,2,3,4,5.
{
// write this in terms of a recursive call using a smaller n
ArrayList<Integer> tempList = null;
if (n <= 0) // The smallest list we can make
{
return new ArrayList<Integer>();
}
else // All other size lists are created here
{
tempList= buildList(n-1);
tempList.add(n);
}
return tempList;
}
This is the problem method.这就是问题方法。 Idk why it returns [], I think there is a passing error.
Idk 为什么它返回 [],我认为有一个传递错误。
public static ArrayList<Integer> reverse(ArrayList<Integer> lst)//the problem method
{
if(lst.size()<=0) {
}
else {
reversedList.add(lst.remove(lst.size()-1));
reverse(lst);
}
return reversedList;
}
public static void main(String[] args)
{
ArrayList<Integer> lst = Recursive.buildList(5);
System.out.println(lst);
reverse(lst);
System.out.println(lst);
}
}
The reverse method removes the last item of lst and adds it to the empty reversedList. reverse 方法删除 lst 的最后一项并将其添加到空的 reversedList 中。 After the first iteration the contents should be [5].
第一次迭代后,内容应为 [5]。 Second [5,4]...all the way to [5,4,3,2,1].
第二个 [5,4]...一直到 [5,4,3,2,1]。 But somehow it ends up being [].
但不知何故,它最终成为[]。 So the reverse method is supposed to print out [5,4,3,2,1] but rather prints [].
所以反向方法应该打印出[5,4,3,2,1],而是打印[]。 I think it has something to do with passing the reversedList between the if and else statement but I'm not sure.
我认为这与在 if 和 else 语句之间传递 reversedList 有关,但我不确定。
You are printing the original list lst only which is now empty as program has removed all the elements.您正在打印原始列表lst ,该列表现在为空,因为程序已删除所有元素。
You must reassign the lst to new object reference returned from function like lst = reverse(lst);您必须将lst重新分配给从 function 返回的新 object 引用,例如lst = reverse(lst);
OR you can use System.out.println(reversedList)或者你可以使用System.out.println(reversedList)
public static void main(String[] args)
{
ArrayList<Integer> lst = Recursive.buildList(5);
System.out.println(lst);
lst = reverse(lst); ////update lst reference
System.out.println(lst);
System.out.println(reversedList); //// OR print reversedList directly
}
Hope you find it helpful.希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.