0

I want to take backup of my 2d array and is there any way how to do this? and how to remove all elements of array ?

int arryNumbers[][]= new int[4][5];
user4441
  • 67
  • 1
  • 9

3 Answers3

1

you can clear array by Loop over the array and and set each element to null.

For String Case:

for( int i = 0; i < arryNumbers.length; i++ )
   Arrays.fill( arryNumbers[i], null );

For int Case:

for (int row = 0; row < ROW.length; row++) {
   for (int col = 0; col < COL.length; col++) {
      arry[row][col] = 0;
   }
}

you take backup by taking (Deep Copy) of your array.

Deep Copy Code:

public int[][] copy(int[][] input) {
      int[][] target = new int[input.length][];
      for (int i=0; i <input.length; i++) {
        target[i] = Arrays.copyOf(input[i], input[i].length);
      }
      return target;
}
Ahmad
  • 1,462
  • 5
  • 17
  • 40
1

Take a backup : arrayNumbers.clone();

To remove all elements, I guess you should do it yourself with "for" loops statements. (Or set it to null and instantiate it again)

MedAl
  • 457
  • 3
  • 19
0

Probably not what you are looking for but does what you ask in probably the fastest way:

int[][] newArray = oldArray;
oldArray=new int[4][5];

This is the fastest way to achieve what you describe. Note that initializing a new array sets the values to '0' in the case of int or 'null' inthe case of objects.

PS. if old oldArray is not symmetric then you can just iterate and initialize each "row" independently.

Ioannis Deligiannis
  • 2,679
  • 5
  • 25
  • 48