Pass an Array to a Constructor without declaring it?

蹲街弑〆低调 提交于 2019-12-01 06:12:02

问题


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!


回答1:


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!!



来源:https://stackoverflow.com/questions/18482953/pass-an-array-to-a-constructor-without-declaring-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!