如何实现可迭代接口?

2022-08-31 20:18:11

给定以下代码,如何循环访问 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);
     }
}

答案 1

可迭代是一个通用接口。您可能遇到的一个问题(您实际上还没有说出您遇到的问题(如果有的话)是,如果您使用泛型接口/类而不指定类型参数,则可以擦除类中不相关的泛型类型的类型。这方面的一个示例是在非泛型类的非泛型引用中,结果为非泛型返回类型

所以我至少会把它改成:

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 类型,因此只有这样才能工作:

for (Object profile : m_PC) {
    // do stuff
}

这是Java泛型的一个非常晦涩难懂的角落案例。

如果没有,请提供有关正在发生的事情的更多信息。


答案 2

首先:

public class ProfileCollection implements Iterable<Profile> {

第二:

return m_Profiles.get(m_ActiveProfile);