什么是“:”?在这个初学者 java 示例程序中使用泛型做什么?
好吧,我需要帮助理解一些事情。我理解“?:”是如何一起使用的,但是阅读一些 Java 入门资料后,我发现这种情况在一些地方出现。最近的是这个......
public static <U> void fillBoxes(U u, List<Box<U>> boxes) {
for (Box<U> box : boxes) {
box.add(u);
}
}
我感到困惑的是“:”到底在做什么。任何帮助将不胜感激。我正在 Oracle 网站的页面上查看此示例,该网站位于: http ://download.oracle.com/javase/tutorial/java/generics/genmethods.html
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这就是 Java 的 for-each 循环结构。它与泛型本身无关或者:不专门与泛型一起使用。它的简写是:
对于名为boxes的集合中的每个类型框执行以下操作...
这是官方文档链接。
更简单的代码示例:(而不是管理泛型执行 int 数组的求和)
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)
这就是
for
循环的“foreach”形式。它是用于获取集合上的迭代器并迭代整个集合的语法糖。这是编写类似内容的快捷方式:
有关更多信息,请参阅 此 Oracle page 专门讨论了“foreach”循环。
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 more see this Oracle page which specifically talks about the "foreach" loop.
它用于迭代容器,在本例中是一个列表。它对
boxes
变量中的每个对象执行一次循环。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.这是 Java 1.5 中添加的增强的 for-each 循环,用于有效地迭代集合的元素。
更多详细说明可参见 Java 文档指南本身。http://download.oracle.com/javase/1.5.0/docs/guide/language/foreach.html
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