Pass Arraylist as argument to function [closed]

混江龙づ霸主 提交于 2019-12-21 07:02:46

问题


I have an arraylist A of Integer type. I created it as:

ArrayList<Integer> A = new ArrayList<Integer>();

Now, I want to pass it as an argument to function AnalyseArray().

How can I achieve this?


回答1:


public void AnalyseArray(ArrayList<Integer> array) {
  // Do something
}
...
ArrayList<Integer> A = new ArrayList<Integer>();
AnalyseArray(A);



回答2:


The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.

<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
{
//analyse the list
//return value
}

call it like this:

x=AnalyseArray(list);

or pass a copy of ArrayList:

x=AnalyseArray(list.clone());



回答3:


Define it as

<return type> AnalyzeArray(ArrayList<Integer> list) {



回答4:


It depends on how and where you declared your array list. If it is an instance variable in the same class like your AnalyseArray() method you don't have to pass it along. The method will know the list and you can simply use the A in whatever purpose you need.

If they don't know each other, e.g. beeing a local variable or declared in a different class, define that your AnalyseArray() method needs an ArrayList parameter

public void AnalyseArray(ArrayList<Integer> theList){}

and then work with theList inside that method. But don't forget to actually pass it on when calling the method.AnalyseArray(A);

PS: Some maybe helpful Information to Variables and parameters.



来源:https://stackoverflow.com/questions/17125270/pass-arraylist-as-argument-to-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!