问题描述
鉴于以下代码,我如何迭代 ProfileCollection 类型的对象?
Given the following code, how can I iterate over an object of type 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);
}
}
推荐答案
Iterable 是一个泛型接口.您可能遇到的一个问题(您实际上并没有说您遇到了什么问题,如果有的话)是,如果您使用泛型接口/类而不指定类型参数,您可以删除不相关的泛型类型的类型班内.这方面的一个例子是 对泛型类的非泛型引用导致非泛型返回类型.
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.
所以我至少会把它改成:
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);
}
}
这应该有效:
for (Profile profile : m_PC) {
// do stuff
}
如果没有 Iterable 上的类型参数,迭代器可能会被简化为 Object 类型,所以只有这样才能工作:
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
for (Object profile : m_PC) {
// do stuff
}
这是 Java 泛型的一个非常晦涩的极端案例.
This is a pretty obscure corner case of Java generics.
如果没有,请提供更多关于发生了什么的信息.
If not, please provide some more info about what's going on.
这篇关于如何实现 Iterable 接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!