返回 ArrayList 并在另一个方法中使用它 [英] Return ArrayList and use it in another method
问题描述
我有一个方法可以返回对象的 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 方法说对象的 Position(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.
有人可以帮助我吗?
推荐答案
如果您在提供它的(看不见的)方法中创建 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 并在另一个方法中使用它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!