Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple way to re-assign values in an array

Tags:

java

arrays

I'm having trouble reassigning values in an array.

    public static void main(String[] {

            int[] arrayOfIntegers = new int[4];
            arrayOfIntegers[0] = 11;
            arrayOfIntegers[1] = 12;
            arrayOfIntegers[2] = 13;
            arrayOfIntegers[3] = 14;

            arrayOfIntegers = {11,12,15,17};

    }

Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?

like image 697
dock_side_tough Avatar asked Dec 15 '22 07:12

dock_side_tough


1 Answers

Why am I unable to reassign values in the manner that I've attempted? If I can't do it, why can't I do it?

Because Java doesn't have destructuring assignment like some other languages do.

Your choices are:

  1. Assign a new array to the array variable as shown by Rohit and Kayaman, but that's not what you asked. You said you wanted to assign to the elements. If you assign a new array to ArrayOfIntegers, anything else that has a reference to the old array in a different variable or member will still refer to the old array.

  2. Use System.arraycopy, but it involves creating a temporary array:

     System.arraycopy(new int[]{11,12,15,17},
                      0,
                      ArrayOfIntegers,
                      0,
                      ArrayOfIntegers.length);
    

System.arraycopy will copy the elements into the existing array.

like image 191
T.J. Crowder Avatar answered Dec 17 '22 21:12

T.J. Crowder