2

I'm having difficulty copying string array values into a new string array.

For example:

String[][] array = new String[3][2];
array[0][0] = "hello";
array[0][1] = "1";
array[1][0] = "guys";
array[1][1] = "2";
array[2][0] = "good ";
array[2][1] = "3";

array = new String [5][2];
all the value in the first array to be copied
array[3][0] = "";
array........;

I tried this method but it keeps me giving null pointer issues whenever I want to insert a new value.

String[][] array = new String[3][2];
array[0][0] = "olo";
array[0][1] = "ada ";
array[1][0] = "apa";
array[1][1] = "dengan";
array[2][0] = "si ";
array[2][1] = "carlo";


String[][] newArray = new String[5][2];
newArray = Arrays.copyOf(array, 5);
array = new String[5][2];
array = Arrays.copyOf(newArray, 5);
array[3][0] = "lo";
array[3][1] = "gw";
array[4][0] = "end";
array[4][1] = "ennnnnd";

for (int r = 0; r < array.length; r++) {
    for (int c = 0; c < array[r].length; c++) {
        System.out.print(" " + array[r][c]);
    }
    System.out.println("");
}

How can I copy this 2d string array?

0

3 Answers 3

9

Java has a built in function called arraycopy that can do this for you without a double for loop. Much more efficient.

Sign up to request clarification or add additional context in comments.

2 Comments

You still have to call arraycopy for the second dimension items. right?
btw how to call the second dimmension for copying
1

First of all the newer array has more elements that source array so decide what you want to do about it. Also if old array is called array call the new array by a different name say newarray.

for ( int i = 0; i < 3; ++i )
{
  for( int j = 0; j < 2; ++i )
  {
      newarray[i][j] = array[i][j];
  }
}

2 Comments

what if I want that both array having the same name is there any ways to do so ? thanks
you can copy it into a newarray. and then do array=newarray. To copy you need to ability to refer to both source and destination , if they are both called the same it might kinda get tricy
0

You can use Arrays.copyOfRange(String param, fromIndex, toIndex)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.