How to add multiple values to array within class?

I have the following array:

class Foo {
  int[] myArray;
  int val1;
  int val2;
  int val3;
  int val4;

  Foo(int val1, int val2, int val3, int val4) {
    this.myArray = new int[4];
    myArray = val1, val2, val3, val4;
  }
}

But I get the error message “Syntax Error - Missing operator, semicolon, or ‘}’ near ‘,’?” How can I add values to my array? I read that the .append method is inefficient (and I’m using the array mostly for efficiency).

void setup() {
  println(new Foo(10, 20, 30, 40).myArray);
  exit();
}

class Foo {
  int[] myArray;

  Foo(int val1, int val2, int val3, int val4) {
    myArray = new int[] { 
      val1, val2, val3, val4
    };
  }
}
void setup() {
  println(new Foo(10, 20, 30, 40).myArray);
  exit();
}

class Foo {
  int[] myArray;

  Foo(int... vals) {
    myArray = vals;
  }
}
1 Like

Are these two alterantive options @GoToLoop? Why can’t I specify the length of the array with new int[4]?

Yes. 1st example is your fixed code. While 2nd 1 is an alternative using variable arguments.

The statement this.myArray = new int[4]; is correct.

However the following myArray = val1, val2, val3, val4; isn’t valid Java syntax!

Once a Java array is created we’d have to initialize each index 1 by 1:

  Foo(int val1, int val2, int val3, int val4) {
    myArray = new int[4];

    myArray[0] = val1;
    myArray[1] = val2;
    myArray[2] = val3;
    myArray[3] = val4;
  }

Therefore my recommendation is to go w/ either of my 2 examples for a shorter code.

More about Java array creation & initialization:
docs.Oracle.com/javase/tutorial/java/nutsandbolts/arrays.html

1 Like

This works perfectly. Thanks :slight_smile: