問題描述
鑒于以下代碼,我如何迭代 ProfileCollection 類型的對象?
Given the following code, how can I iterate over an object of type 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 是一個泛型接口.您可能遇到的一個問題(您實際上并沒有說您遇到了什么問題,如果有的話)是,如果您使用泛型接口/類而不指定類型參數,您可以刪除不相關的泛型類型的類型班內.這方面的一個例子是 對泛型類的非泛型引用導致非泛型返回類型.
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);
}
}
這應該有效:
for (Profile profile : m_PC) {
// do stuff
}
如果沒有 Iterable 上的類型參數,迭代器可能會被簡化為 Object 類型,所以只有這樣才能工作:
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
}
這是 Java 泛型的一個非常晦澀的極端案例.
This is a pretty obscure corner case of Java generics.
如果沒有,請提供更多關于發生了什么的信息.
If not, please provide some more info about what's going on.
這篇關于如何實現 Iterable 接口?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!