簡體   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