문제
다음 코드가 주어지면 유형의 프로파일 컬렉션 대상을 어떻게 반복 할 수 있습니까?
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);
}
}
해결책
반복 가능한 것은 일반적인 인터페이스입니다. 당신이 가질 수있는 문제 (실제로 어떤 문제가 있는지 말하지 않은 경우) 유형 인수를 지정하지 않고 일반 인터페이스/클래스를 사용하는 경우 관련없는 일반 유형의 유형을 지울 수 있다는 것입니다. 수업 내에서. 이것의 예가 있습니다 제네릭 클래스에 대한 비 게 니체 참조는 비 게 니체 리턴 유형을 초래합니다..
그래서 나는 적어도 다음으로 바꿀 것입니다.
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
}
반복 가능한 유형의 인수가 없으면 반복기가 유형 객체로 축소 될 수 있으므로 이렇게하면 다음과 같이 작동합니다.
for (Object profile : m_PC) {
// do stuff
}
이것은 Java Generics의 매우 모호한 코너 케이스입니다.
그렇지 않다면 무슨 일이 일어나고 있는지에 대한 자세한 정보를 제공하십시오.
다른 팁
우선:
public class ProfileCollection implements Iterable<Profile> {
초:
return m_Profiles.get(m_ActiveProfile);
제휴하지 않습니다 StackOverflow