Okay so I need help understanding something. I understand how "? :" are used together but reading over some beginning Java stuff I see this situation popping up in a few places. Most recently is this...
public static <U> void fillBoxes(U u, List<Box<U>> boxes) {
for (Box<U> box : boxes) {
box.add(u);
}
}
What I am confused about is what exactly ":" is doing. Any help would be appreciated. I am looking at this example on a page at Oracle's website, located here: http://download.oracle.com/javase/tutorial/java/generics/genmethods.html
That is Java's for-each looping construct. It has nothing to do with generics per-se or: is not for use exclusively with generics. It's shorthand that says: for every type box in the collection named boxes do the following...
Here's the link to the official documentation.
Simpler code sample: (instead of managing generics performing a summation of an int array)
int[] intArray = {1,5,9,3,5};
int sum = 0;
for (int i : intArray) sum += i;
System.out.println(sum);
Output: 23
That's the "foreach" form of the for
loop. It is syntactic sugar for getting an iterator on the collection and iterating over the entire collection.
It's a shortcut to writing something like:
for (Iterator<Box<U>> it = boxes.iterator(); it.hasNext(); ) {
Box<U> box = it.next();
box.add(u);
}
For more see this Oracle page which specifically talks about the "foreach" loop.
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