We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hi All,
here's a sample code:
void setup() {
}
void draw() {
int[] a = {1, 2, 3, 4, 5};
arrayMethod(a);
a = {6, 7, 8, 9, 10};
arrayMethod(a);
}
void arrayMethod(int[] a) {
for (int i=0; i<a.length; i++) {
println(a[i]);
}
}
Why can I not redefine the elements of array a using curly brackets at line 7? Is there a way to assign values to the elements of an array without using:
a[0] = 1;
a[1] = 2;
a[2] = 3;
...
? Isn't merely writing {1, 2, 3, 4, 5} enough to tell Processing I'm using an array datatype? Mmmhh... is an array even a datatype?
Answers
This is going to be an unsatisfying answer, but you can't do it because, well, you aren't allowed. That's just not valid syntax, because the designers of Java decided that it shouldn't be.
To get around this restriction, you can use the
new int[]
syntax to create a new array:Pity! :) I'm sure they had good reasons. Many thanks, the workaround you've shown me will do just fine for what I'm cobbling together.
The simplified array creation, à la C language, w/o specifying its datatype, is available only when we declare the variable together. ~O)
Kf
GoToLoop, okay. Although I only meant to alter the elements of an existing array, not really to create one without specifying its datatype. But I guess another advantage of the need to "recreate" the array every time is that I can also change its length. And it's not much more typing to do.
kfrajer, thanks for the FloatList example. So, a FloatList and an float array are the same thing (line 4 of your example)?