Java 如何实现 Iterable 接口?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/601658/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I implement the Iterable interface?
提问by Dewayne
Given the following code, how can I iterate over an object of type ProfileCollection?
给定以下代码,如何遍历 ProfileCollection 类型的对象?
public class ProfileCollection implements Iterable {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
public static void main(String[] args) {
m_PC = new ProfileCollection("profiles.xml");
// properly outputs a profile:
System.out.println(m_PC.GetActiveProfile());
// not actually outputting any profiles:
for(Iterator i = m_PC.iterator();i.hasNext();) {
System.out.println(i.next());
}
// how I actually want this to work, but won't even compile:
for(Profile prof: m_PC) {
System.out.println(prof);
}
}
采纳答案by cletus
Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.
Iterable 是一个通用接口。您可能遇到的一个问题(您实际上还没有说您遇到了什么问题,如果有的话)是,如果您使用泛型接口/类而不指定类型参数,您可以删除不相关泛型类型的类型班级内。这方面的一个例子是对泛型类的非泛型引用导致非泛型返回类型。
So I would at least change it to:
所以我至少会把它改成:
public class ProfileCollection implements Iterable<Profile> {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
and this should work:
这应该有效:
for (Profile profile : m_PC) {
// do stuff
}
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
如果没有 Iterable 的类型参数,迭代器可能会被简化为 Object 类型,所以只有这样才能工作:
for (Object profile : m_PC) {
// do stuff
}
This is a pretty obscure corner case of Java generics.
这是 Java 泛型的一个非常晦涩的角落案例。
If not, please provide some more info about what's going on.
如果没有,请提供一些有关正在发生的事情的更多信息。
回答by TofuBeer
First off:
首先:
public class ProfileCollection implements Iterable<Profile> {
Second:
第二:
return m_Profiles.get(m_ActiveProfile);