如何实现Iterable接口?

Dew*_*yne 52 java iterator

给定以下代码,如何迭代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);
     }
}
Run Code Online (Sandbox Code Playgroud)

cle*_*tus 59

Iterable是一个通用接口.您可能遇到的问题(您实际上没有说过您遇到的问题,如果有的话)是,如果您使用通用接口/类而未指定类型参数,则可以删除不相关的泛型类型的类型在课堂上.这方面的一个例子是非泛型引用非泛型返回类型中的泛型类结果.

所以我至少会改为:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这应该工作:

for (Profile profile : m_PC) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

如果没有Iterable上的类型参数,迭代器可以简化为Object类型,因此只有这样才能工作:

for (Object profile : m_PC) {
    // do stuff
}
Run Code Online (Sandbox Code Playgroud)

这是Java泛型的一个相当模糊的角落案例.

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

  • 只是警告你的方法; 如果你只是从ArrayList转发迭代器,你也可以转发删除项目的能力.如果您不想这样,则必须包装迭代器,或将ArrayList包装为只读集合. (5认同)
  • 我认为他指的是:Collections.unmodifiableList(m_profiles).iterator().这将停止调用者修改arraylist (4认同)