I'm guessing it does not work, because in the syntax the first parameter must have a declared type. But what if I'm using a for-each loop in a function with an argument like I am in this example? The variable p
has a declared type, I just want to reuse it.
public void addItem(Product p) {
// ensure that we don't add any nulls to the item list
if (p != null ) {
int i = 0;
for (p : items.keySet()) {
i++;
}
items.put( p , i);
}
}
There is a related question, Java for loop syntax: "for (T obj : objects)". That one asks what the for-each syntax means. I know what it means, I just want to reuse an existing variable rather than having to declare a new one.