Pass an Array to a Constructor without declaring it?

て烟熏妆下的殇ゞ 提交于 2019-12-01 09:10:18

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

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