Array redefinition

edited March 2018 in Questions about Code

Hi All,

here's a sample code:

void setup() {
}

void draw() {
  int[] a = {1, 2, 3, 4, 5};
  arrayMethod(a);
  a = {6, 7, 8, 9, 10};
  arrayMethod(a);
}

void arrayMethod(int[] a) {
  for (int i=0; i<a.length; i++) {
    println(a[i]);
  }
}

Why can I not redefine the elements of array a using curly brackets at line 7? Is there a way to assign values to the elements of an array without using:

a[0] = 1;
a[1] = 2;
a[2] = 3;
...

? Isn't merely writing {1, 2, 3, 4, 5} enough to tell Processing I'm using an array datatype? Mmmhh... is an array even a datatype?

Tagged:

Answers

  • This is going to be an unsatisfying answer, but you can't do it because, well, you aren't allowed. That's just not valid syntax, because the designers of Java decided that it shouldn't be.

    To get around this restriction, you can use the new int[] syntax to create a new array:

    int[] a = {1, 2, 3, 4, 5};
    a = new int[]{6, 7, 8, 9, 10};
    
  • Pity! :) I'm sure they had good reasons. Many thanks, the workaround you've shown me will do just fine for what I'm cobbling together.

  • The simplified array creation, à la C language, w/o specifying its datatype, is available only when we declare the variable together. ~O)

  • //FloatList fl1 = new FloatList( {5,6.3,6.6} );  //NOT VALID
    
    float[] all={1,2.2,3.3};
    FloatList fl2 = new FloatList(all);  //WORKS/valid
    
    FloatList fl3 = new FloatList(new float[5]);
    println(fl3.toString());  //PRINTS: FloatList size=5 [ 0.0, 0.0, 0.0, 0.0, 0.0 ]
    

    Kf

  • GoToLoop, okay. Although I only meant to alter the elements of an existing array, not really to create one without specifying its datatype. But I guess another advantage of the need to "recreate" the array every time is that I can also change its length. And it's not much more typing to do.

    kfrajer, thanks for the FloatList example. So, a FloatList and an float array are the same thing (line 4 of your example)?

Sign In or Register to comment.