Pregunta

Dado el siguiente código, ¿cómo puedo iterar sobre un objeto de tipo 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);
     }
}
¿Fue útil?

Solución

Iterable es una interfaz genérica. Un problema que puede tener (en realidad no ha dicho qué problema tiene, si lo hubiera) es que si usa una interfaz / clase genérica sin especificar el tipo de argumento (s), puede borrar los tipos de tipos genéricos no relacionados. dentro de la clase Un ejemplo de esto está en Referencia no genérica a resultados de clase genéricos en tipos de devolución no genéricos .

Así que al menos lo cambiaría a:

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

y esto debería funcionar:

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

Sin el argumento de tipo en Iterable, el iterador puede reducirse a ser Objeto de tipo, por lo que solo funcionará:

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

Este es un caso de esquina bastante oscuro de los genéricos de Java.

Si no es así, proporcione más información sobre lo que está pasando.

Otros consejos

Primero apagado:

public class ProfileCollection implements Iterable<Profile> {

Segundo:

return m_Profiles.get(m_ActiveProfile);
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top