如何实现Iterable接口? [英] How can I implement the Iterable interface?

查看:745
本文介绍了如何实现Iterable接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于以下代码,我如何迭代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上的type参数,迭代器可能会被简化为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接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆