Java 反向方法应反向打印lst。它将打印一个空的arrayList。为什么会发生这种情况,我该如何解决?
这是具有buildList方法的类,该方法在Java 反向方法应反向打印lst。它将打印一个空的arrayList。为什么会发生这种情况,我该如何解决?,java,recursion,reverse,Java,Recursion,Reverse,这是具有buildList方法的类,该方法在 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 t
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;
}
类递归
{
公共静态ArrayList reversedList=新建ArrayList();
公共静态ArrayList buildList(int n)//基于整数构建ArrayList。如果int为5,则内容为1,2,3,4,5。
{
//用一个较小的n来编写递归调用
ArrayList tempList=null;
如果(n您仅打印原始列表,该列表现在为空,因为程序已删除所有元素 必须将lst重新分配给从函数返回的新对象引用,如lst=reverse(lst); 或者您可以使用System.out.println(反向列表)
publicstaticvoidmain(字符串[]args)
{
ArrayList lst=Recursive.buildList(5);
系统输出打印项次(lst);
lst=反向(lst);///更新lst引用
系统输出打印项次(lst);
System.out.println(reversedList);///或直接打印reversedList
}
希望对您有所帮助。您打印出了原始列表,现在没有项目了。非常感谢。因此,由于lst变量的所有对象都已删除,因此我必须将其重新分配给反向(lst),以便它将与反向列表相等,从而具有其内容?是的。因此,lst和反向列表都将引用同一个对象
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);
}
}
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
}