繁体   English   中英

reverse 方法应该反向打印出 lst 。 它改为打印一个空的 arrayList。 为什么会发生这种情况,我该如何解决?

[英]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?

这是带有 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;

    }

这就是问题方法。 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);


    }

}

reverse 方法删除 lst 的最后一项并将其添加到空的 reversedList 中。 第一次迭代后,内容应为 [5]。 第二个 [5,4]...一直到 [5,4,3,2,1]。 但不知何故,它最终成为[]。 所以反向方法应该打印出[5,4,3,2,1],而是打印[]。 我认为这与在 if 和 else 语句之间传递 reversedList 有关,但我不确定。

您正在打印原始列表lst ,该列表现在为空,因为程序已删除所有元素。

您必须将lst重新分配给从 function 返回的新 object 引用,例如lst = reverse(lst);

或者你可以使用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 
    }

希望对您有所帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM