What is ":" doing in this beginners java example program using generics?
Okay so I need help unders开发者_如何学运维tanding 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.
It is used to iterate over the container, in this case a List. It executes the loop once for each object in the boxes
variable.
This is an enhanced for-each loop added in Java 1.5 to iterate efficiently through elements of collections.
Further detailed explanation is available at Java doc guide itself.http://download.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
精彩评论