david
david

Reputation: 83

Replacing an entire array in one fell swoop.

I have an array A of size 10 and another array B of size 5.

Both have the same elements, except array A has 5 more null elements. Can we replace the value of pointer A to pointer B like this:

arrayA = arrayB;

Upvotes: 2

Views: 11692

Answers (5)

Bohemian
Bohemian

Reputation: 425063

The closest thing to a fell swoop is this one-liner:

System.arrayCopy(arrayA, 0, arrayB, 0, arrayB.length);

Upvotes: 2

Sam Su
Sam Su

Reputation: 6832

You should use System.arraycopy.

public class SystemDemo {

   public static void main(String[] args) {

      int arr1[] = { 1, 2, 3, 4, 5 };
      int arr2[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
      System.arraycopy(arr2, 5, arr1, 0, 5);

      for (int i : arr1) {
          System.out.println(i);
      }
   }
}

Then you will get a result:

6
7
8
9
10 

Upvotes: 1

Sri Harsha Chilakapati
Sri Harsha Chilakapati

Reputation: 11950

You can change references for that. http://ideone.com/Rl3u4k

The snippet is

import java.util.*;
import java.lang.*;

class Main
{
    public static void main (String[] args) throws java.lang.Exception
    {
        // array1 having three null elements
        String[] array1 = new String[]{ "hello", "world", "from", "array1", null, null, null };
        // array2 having no null elements
        String[] array2 = new String[]{ "hi", "this", "is", "array2" };

        // print array1
        for (String value : array1)
        {
            System.out.println(value);
        }

        // swap values
        array1 = array2;

        // print array1 again
        for (String value : array1)
        {
            System.out.println(value);
        }
    }
}

The output is

// before changing
hello
world
from
array1
null
null
null
// after changing reference
hi
this
is
array2

Upvotes: 1

arynaq
arynaq

Reputation: 6870

No that would simply make the variable arrayA refer to arrayB (and lose its original reference to whatever array it was holding, data lost). You would need to copy it like so:

String[] a = ....
String[] b = new String[a.length];
System.arraycopy(a,0,b,0, a.length);

Note this copies a.length elements from index 0, the whole array.

Upvotes: 2

TomSelleck
TomSelleck

Reputation: 6968

arrayA = arrayB;

Will make arrayA a reference to arrayB. There are no pointers in Java.

Upvotes: 3

Related Questions