【问题标题】:Is it possible to copy an array while looping through it? java循环遍历数组时是否可以复制数组?爪哇
【发布时间】:2015-09-24 08:01:15
【问题描述】:

有没有一种方法可以在循环遍历数组时复制它?

所以,我想在循环过程还没有完成的情况下,将刚刚添加到数组中的当前元素的副本发送到类中的另一个方法来处理它,然后返回到前面的循环中方法。

我假设,如果可能的话,它可能是这样的:

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.

【问题讨论】:

  • 为什么你认为它不可能?试了有没有报错?
  • 是的,你可以这样做。
  • @Henry 它给了我一个没有元素的空副本
  • for (loop): 我希望这不是你的实际代码。
  • @NickJ 哈哈哈!我希望一样

标签: java arrays


【解决方案1】:
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 并检查。它工作正常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 2014-06-04
    • 1970-01-01
    • 2019-07-10
    • 1970-01-01
    相关资源
    最近更新 更多