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!
[Java] How to pass int[] array in an object constructor. //Number. java public class Number { private int[] Numbers = new int[3]; public Number(int[] array) { this. Numbers = array; } } //Setter.
To pass an array to a constructor we need to pass in the array variable to the constructor while creating an object.
An Array in Java is an Object just like everything else (except primitives) and is on the heap. When you call new int[100000] you're creating a new object just like every other object, and it gets initialized, etc. So, no. You can't avoid "initializing" an array.
In C++, we can pass arrays as an argument to a function. And, also we can return arrays from a function. Before you learn about passing arrays as a function argument, make sure you know about C++ Arrays and C++ Functions.
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!!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With