返回ArrayList并在其他方法中使用它

编程入门 行业动态 更新时间:2024-10-26 23:28:41
本文介绍了返回ArrayList并在其他方法中使用它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个返回对象的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并在其他方法中使用它

本文发布于:2023-07-16 16:09:35,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1123420.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:并在   方法   使用它   ArrayList

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!