Подтвердить что ты не робот

Как я могу реализовать интерфейс Iterable?

Учитывая следующий код, как я могу перебирать объект типа 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);
     }
}
4b9b3361

Ответ 1

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

и это должно работать:

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

Без аргумента type в Iterable, итератор может быть сведен к типу Object, поэтому только это будет работать:

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

Это довольно неясный угловой случай Java-дженериков.

Если нет, предоставьте дополнительную информацию о том, что происходит.

Ответ 2

Прежде всего:

public class ProfileCollection implements Iterable<Profile> {

Второе:

return m_Profiles.get(m_ActiveProfile);