How can I implement the Iterable interface?

前端 未结 2 1747
野的像风
野的像风 2020-11-29 21:21

Given the following code, how can I iterate over an object of type ProfileCollection?

public class ProfileCollection implements Iterable {    
    private Ar         


        
相关标签:
2条回答
  • 2020-11-29 22:06

    First off:

    public class ProfileCollection implements Iterable<Profile> {
    

    Second:

    return m_Profiles.get(m_ActiveProfile);
    
    0 讨论(0)
  • 2020-11-29 22:12

    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);
        }
    }
    

    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:

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

    This is a pretty obscure corner case of Java generics.

    If not, please provide some more info about what's going on.

    0 讨论(0)
提交回复
热议问题