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

StackOverflow https://stackoverflow.com/questions/601658

  •  03-07-2019
  •  | 
  •  

Вопрос

Учитывая следующий код, как я могу выполнить итерацию по объекту типа 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 - это универсальный интерфейс.Проблема, с которой вы можете столкнуться (вы на самом деле не сказали, с какой проблемой вы столкнулись, если таковые имеются), заключается в том, что если вы используете универсальный интерфейс / класс без указания аргументов типа, вы можете стереть типы несвязанных универсальных типов внутри класса.Примером этого является Неуниверсальная ссылка на универсальный класс приводит к получению неуниверсальных возвращаемых типов.

Так что я бы, по крайней мере, изменил его на:

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 generics.

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

Другие советы

Во-первых:

public class ProfileCollection implements Iterable<Profile> {

Второй:

return m_Profiles.get(m_ActiveProfile);
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top