我有一个返回对象的ArrayList的方法.我返回创建的arraylist,并用许多对象填充它,然后通过用相同的方法打印它们来检查它们是否存在.当我在另一个方法中将该Arraylist用作参数时,它给我一个错误,就像arraylist为空一样.
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.
让我们使用方法getFila和getColumna将对象的位置(y,x)说出来. 失败的方法(实际上什么也没做):
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; }我返回了其中包含许多对象的Arraylist,但是我不知道这是怎么回事.
I return the Arraylist with many objects inside, but I dont know what is happening with that.
摘要:
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?
推荐答案如果您正在使用提供它的(看不见的)方法创建ArrayList,您是否要返回它?还是您要修改参数?
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或者您正在这样做:
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.
更多推荐
返回ArrayList并在其他方法中使用它
发布评论