Home > Mobile >  JAVA: How to copy arrays? [closed]
JAVA: How to copy arrays? [closed]

Time:09-26

I am trying to copy arrays here is my code example:

    int [] boom = {10,2,3,4,20,435354,657657,23,213,43543,567};
    int[] boom1 = {};

    for(int i=0;i< boom.length;i  ){
        boom[i] = i;
    }
    for(int i=0;i< boom.length;i  ) {
        boom1[i]=boom[i];
    }

    System.out.println(Arrays.toString(boom1));

But after compiling it is giving me error:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0

How to solve this?

CodePudding user response:

Why not just use the Arrays.copyOf method:

int[] boom  = {10,2,3,4,20,435354,657657,23,213,43543,567};
int[] boom1 = Arrays.copyOf(boom, boom.length);
System.out.println(Arrays.toString(boom1));

CodePudding user response:

you have to define the size of the boom1[] as boom.lenght(),

take a look at this code:

public static void main(String[] args)
{
    int [] boom = {10,2,3,4,20,435354,657657,23,213,43543,567};

    // Create an array boom1[] of same size as boom[]
    int boom1[] = new int[boom.length];

    // Copy elements of boom[] to boom1[]
    for (int i = 0; i < boom.length; i  )
        boom1[i] = boom[i];


    System.out.println("Contents of boom[] ");
    for (int i = 0; i < boom.length; i  )
        System.out.print(boom[i]   " ");

    System.out.println("\n\nContents of boom1[] ");
    for (int i = 0; i < boom1.length; i  )
        System.out.print(boom1[i]   " ");
}
  • Related