Search code examples
javamethodsarraylistreturn

Return ArrayList and use it in another method


I have a method that returns an ArrayList of Objects. I return the arraylist created, and its filled with many objects, that I check they are there by printing them in the same method. When I use that Arraylist as parameter in another method, it gives me an error, like if the arraylist were empty.

Lets say the object its Position(y,x), with methods getFila and getColumna. And the method that fails (actually does nothing):

public static ArrayList<Position> getTrayectory (ArrayList<Position> aListPos){
        for (int ii = 0; ii < aListPos.size();ii++ ) {
            System.out.println("(" +  aListPos.get(ii).getFila() + "," + aListPos.get(ii).getColumna()+")");
        }
        return aListPos;
    }

I return the Arraylist with many objects inside, but I dont know what is happening with that.

Summary:

1- I have a method that returns an ArryList
2- I create a new Arraylist with method in 1
3- I use new method with Arraylist in 2 as parameter.

(4-) Nothing happens, because new arraylist in 2 look empty.

Can anyone help me in the process?


Solution

  • If you are creating the ArrayList in the (unseen) method that provides it, are you returning it? Or are you modifying a parameter?

    In other words, are you doing this:

    ArrayList<Position> myArrayList = generateArrayList(); // or whatever you call it
    

    or are you doing this:

    ArrayList<Position> myArrayList;
    generateArrayList(myArrayList);
    ArrayList<Position> result = getTrayjectory(myArrayList);
    

    The second version of this won't work, because when you create an object inside a method, the only way that it can escape the method's bounds is to be returned by that method. Otherwise, it goes out of scope when the method ends.