Ok so i have a program where it sets an array with values and then asks for them at a later time as programs do.
int[] foo = new int[10]; //init array
//also added a getter and setter for this array
setFoo(fooLocal); //setter being implemented
now in another part of my code i want to access these values using a for loop but it seems like this won't really work because you really don't have a place to put the value from the for loop.
for (x = 0; x < getFoo().length; x++){
//this is where i get a bit confused
getFoo(x); //im not really sure what to do here?
}
this answer is probably very simple but i haven't come across anything like it yet. please help or reference would be great thank you :)
Best How To :
Assuming getFoo() returns an the array foo
(which seems to be the case from your for loop statement), you can access index x
of foo
with:
int a = getFoo()[x];
From there, you can use a
as you would any other int.
This is slightly inefficient though, especially if getFoo()
has to do computation of any kind. A slightly more efficient way to do this is to grab a reference to foo
before starting the for loop:
int[] foo = getFoo();
for(int x = 0; x < foo.length; x++){
int a = foo[x];
//do stuff with a
}
Even more concisely, you can use a for-each loop to simply get each element of foo
in turn without worrying about indices. This approach becomes less enticing if you do need the index value, however.
for(int a : getFoo()){
//do stuff with a
}