An easy way to reset values โ€‹โ€‹in an array

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 can't I reassign values โ€‹โ€‹as I tried? If I can't do this, why can't I do this?

+4
source share
4 answers

Why can't I reassign values โ€‹โ€‹as I tried? If I can't do this, why can't I do this?

Because Java does not have a deconstruct destination, as some other languages โ€‹โ€‹do.

Your options:

  • Assign the new array to an array variable, as shown by Rohit and Kayaman, but this is not what you requested. You said you want to assign items. If you assigned a new array to ArrayOfIntegers , everything else that references the old array in another variable or member will still reference the old array.

  • Use System.arraycopy , but it includes creating a temporary array:

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

    System.arraycopy will copy elements to an existing array.

+5
source

You need to specify the type of array. Use this:

 arrayOfIntegers = new int[] {11,12,15,17}; 

From JLS Section 10.6 :

An array initializer can be specified in a declaration (ยง8.3, ยง9.3, ยง14.4) or as part of an array creation expression (ยง15.10) to create an array and provide some initial values.

If you are trying to reassign array elements in a certain range, you cannot do this with direct assignment. Either you need to assign values โ€‹โ€‹by index individually, or use the method specified by @TJCrowder in his answer.

+4
source

The correct syntax is:

 arrayOfIntegers = new int[]{11,12,15,17}; 
+3
source

delicious milk flavor I want it now

-4
source

Source: https://habr.com/ru/post/1497577/


All Articles