問(wèn)題描述
鑒于以下代碼,我如何迭代 ProfileCollection 類型的對(duì)象?
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 是一個(gè)泛型接口.您可能遇到的一個(gè)問(wèn)題(您實(shí)際上并沒(méi)有說(shuō)您遇到了什么問(wèn)題,如果有的話)是,如果您使用泛型接口/類而不指定類型參數(shù),您可以刪除不相關(guān)的泛型類型的類型班內(nèi).這方面的一個(gè)例子是 對(duì)泛型類的非泛型引用導(dǎo)致非泛型返回類型.
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.
所以我至少會(huì)把它改成:
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);
}
}
這應(yīng)該有效:
for (Profile profile : m_PC) {
// do stuff
}
如果沒(méi)有 Iterable 上的類型參數(shù),迭代器可能會(huì)被簡(jiǎn)化為 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 泛型的一個(gè)非常晦澀的極端案例.
This is a pretty obscure corner case of Java generics.
如果沒(méi)有,請(qǐng)?zhí)峁└嚓P(guān)于發(fā)生了什么的信息.
If not, please provide some more info about what's going on.
這篇關(guān)于如何實(shí)現(xiàn) Iterable 接口?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!