将数组传递给构造函数而不声明它? [英] Pass an Array to a Constructor without declaring it?
问题描述
在处理中,我定义了以下类:
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.
但是,这将起作用:
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);
该类的两个实例现在都引用了同一数组{0, 100}
,这肯定不是我想要做的.
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?
谢谢您的回答!
推荐答案
您仍然需要以某种方式对其进行定义,然后再将其发送给...尝试以下操作:
You still need to define it somehow before you send it in... Try this:
SomeClass myVar = new SomeClass(new int [] {
12, 10
});
或者您可以尝试一些Java的语法糖...
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);
数组很有趣!
这篇关于将数组传递给构造函数而不声明它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!