6

In processing, I have defined the following class:

class SomeClass {
    SomeClass(int[] someArray) {
        println(someArray);
    }
}

Now I would like to create an instance of that class, but I am having trouble getting the array passed to the constructor:

SomeClass myVar = new SomeClass({
    12, 10
});

But this always gives me an error "unexpected token: {". So apparently defining the array "on the fly" does not work.

However, this will work:

int[] dummy = {12, 10};

SomeClass myVar = new SomeClass(dummy);

But I find it rather stupid to declare this array outside of the object, because this leads to all kinds of trouble when creating multiple objects:

int[] dummy = {12, 10};
SomeClass myVar = new SomeClass(dummy);

dummy = {0, 100};
SomeClass myVar2 = new SomeClass(dummy);

Both instances of the class now have a reference to the same array {0, 100} which is certainly not what I intended to do.

So my question is: how does one correctly pass an array to the constructor of a class without having to declare the array before? Is it even possible?

Thank you for your answers!

Petros Koutsolampros
  • 2,790
  • 1
  • 14
  • 20
Lars Ebert
  • 3,487
  • 2
  • 24
  • 46

1 Answers1

9

You still need to define it somehow before you send it in... Try this:

SomeClass myVar = new SomeClass(new int [] {
    12, 10
});

or you could try some of Java's syntactic sugar...

class SomeClass {
    SomeClass(int... someArray) {
        println(someArray);
    }
}
SomeClass myVar = new SomeClass(12, 10);

which will introduce some restrictions to your coding style... For example you can do this: (special syntax as the last element)

class SomeClass {
    SomeClass(String someString, float someFloat, int... someArray) {
        println(someString);
        println(someFloat);
        println(someArray);
    }
}
SomeClass myVar = new SomeClass("lol",3.14, 12, 10);

but not this: (special syntax not as the last element)

class SomeClass {
    SomeClass(String someString, int... someArray, float someFloat) {
        println(someString);
        println(someFloat);
        println(someArray);
    }
}
SomeClass myVar = new SomeClass("lol", 12, 10,3.14);

Arrays are fun!!

Petros Koutsolampros
  • 2,790
  • 1
  • 14
  • 20
  • 2
    Actually the first syntax `new int [] {` was exactly what I meant, because I now do not have to store the reference to the array in a variable before. But the `...` syntax is pretty awesome. I am not really fluid in Java but love to use processing - this is an awesome trick! – Lars Ebert Aug 28 '13 at 10:51
  • Either syntax is essentially the same process under the hood, it will just be done automagically! :D – Petros Koutsolampros Aug 28 '13 at 10:55
  • All these years of openly hating, bashing and flaming Java and now I have to admit that I somewhat like Java. ;) – Lars Ebert Aug 28 '13 at 10:59