What is “:” doing in this beginners java example program using generics?

时光总嘲笑我的痴心妄想 提交于 2020-01-03 18:36:13

问题


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


回答1:


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




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/6039211/what-is-doing-in-this-beginners-java-example-program-using-generics

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!