是否可以在循环时复制数组? java的

时间:2015-09-24 08:01:16

标签: java arrays

在循环播放数组时是否存在复制数组的方法?

所以,我想发送刚刚添加到数组中的当前元素的副本,而循环过程仍未完成,类中的另一个方法处理它然后返回到前一个循环方法

我认为,如果可能的话,它可能是这样的:

String[] a = new String[10];

for (loop) {
  a[0] = "Hello";
  anotherMethod(Arrays.copyOf(a, a.length));
  }

 // anotherMethod(a) will get a copy of the array showing the
 // first index of a, which is `Hello`, and will do similarly
 // every time the first loop calls it.

1 个答案:

答案 0 :(得分:0)

import java.util.Arrays;

public class Myclass {

    public static void main(String[] args) {


        String[] array=new String[10]; 

        for(int i=0;i<array.length;i++){

            System.out.println("current counter is:"+i);
            array[i]="text "+String.valueOf(i);
            showStringTextConsole(Arrays.copyOf(array, array.length));
        }


    }

    static void showStringTextConsole(String[] array){

        for (String text:array){
            System.out.println(text);
        }

        System.out.println("----end of array-----");

    }

}

将其复制到IDE并检查。它工作正常。