bowemc
asked on
For Each loop in java?
Hi,
How do you write a foreach loop in java? I' have the below:
for (int i =0; i < categoryId.length; i++)
I presume it would be more efficient etc to use a for each construct if it exists in java?
How do you write a foreach loop in java? I' have the below:
for (int i =0; i < categoryId.length; i++)
I presume it would be more efficient etc to use a for each construct if it exists in java?
ASKER CERTIFIED SOLUTION
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
for each statement need java 1.5 or above
categgoryId must be int array;
a simple sample;
int[] categgoryId = {1, 2, 5};
for(Integer id: categgoryId) {
System.out.print(id + ", ");
}
categgoryId must be int array;
a simple sample;
int[] categgoryId = {1, 2, 5};
for(Integer id: categgoryId) {
System.out.print(id + ", ");
}
The space DOES NOT matter!!
for(int id: categgoryId)
{
}
and
for(int id : categgoryId)
{
}
both will work absolutely fine.
Also, due to the autoboxing feature of Java 5.0, the categoryId can be either an Integer array or int array or List<Integer> or any collection of Integer.
>> s this ok or do I need something like : proc.setInt(3, categoryId[id].value);
if categoryId is an array of int or Integer, you can just use categoryId[i] (again thanks to autoboxing - i.e auto type casting )
If categoryId is a List, you need to do somehting like categoryId.get(i);
You will NOT need to do categoryId[i].value in any case!!
for(int id: categgoryId)
{
}
and
for(int id : categgoryId)
{
}
both will work absolutely fine.
Also, due to the autoboxing feature of Java 5.0, the categoryId can be either an Integer array or int array or List<Integer> or any collection of Integer.
>> s this ok or do I need something like : proc.setInt(3, categoryId[id].value);
if categoryId is an array of int or Integer, you can just use categoryId[i] (again thanks to autoboxing - i.e auto type casting )
If categoryId is a List, you need to do somehting like categoryId.get(i);
You will NOT need to do categoryId[i].value in any case!!
ASKER
I had tried that but had for(int id : categoryId) and it wouldn't compile. Clearly I shouldn't have had a space between id and my ':'
I'm setting a stored proc within my loop like so:
proc.setInt(3, categoryId[id]);
is this ok or do I need something like : proc.setInt(3, categoryId[id].value);
Thanks