简体   繁体   English

同时调用方法时如何向arrayList添加元素?

[英]How to add an element to arrayList when calling the method at the same time?

I am doing a recursive program and I want to call a method 2 times in a row, which looks like this: 我正在做一个递归程序,我想连续两次调用一个方法,如下所示:

print(ArrayList<Integer> current + arr[0], Arrays.copyOfRange(arr, 1, arr.length) );
print(ArrayList<Integer> current, Arrays.copyOfRange(arr, 1, arr.length));

But it is impossible to add a value to the ArrayList like that. 但是不可能像这样向ArrayList添加值。 However, I can't use current.add() outside either, because it will mess up my second call. 但是,我也不能在外面使用current.add(),因为它会弄乱我的第二个电话。 So is there a way to add a value to the arrayList while calling the method, or do I have to think of another way to write my code? 那么有没有一种方法可以在调用方法时向arrayList添加值,还是我必须考虑另一种方式来编写代码?

You may overload your print method like the following: 您可以像下面这样重载打印方法:

public void print(ArrayList<Integer> current, int i, int[] arr ) {
    //print whatever you want
    //then add using current.add(i)
    current.add(i)
}

then call your overloaded print() method in the first time like this: 然后像这样第一次调用重载的print()方法:

print(current, arr[0], arr);

You can achieve it with following code 您可以使用以下代码来实现

print(new ArrayList<Integer>(current) {{ add(arr[0]); }},
      Arrays.copyOfRange(arr, 1, arr.length) );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM