كيف يمكنني تطبيق واجهة Iterable؟
سؤال
ونظرا لالبرمجية التالية، كيف يمكنني تكرار عبر كائن من نوع 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 هو واجهة عامة. وهناك مشكلة قد يكون لها (هل لا وقال في الواقع ما هي المشكلة كنت تواجه، إن وجدت) هي أنه إذا كنت تستخدم واجهة عامة / فئة دون تحديد وسيطة نوع (ق) يمكنك محو أنواع من أنواع عامة لا علاقة لها داخل الطبقة. مثال على ذلك هو في <لأ href = "https://stackoverflow.com/questions/449103/non-generic-reference-to-generic-class-results-in-non-generic-return-types/449115#449115 "> مرجع غير العامة إلى نتائج فئة عامة في أنواع الإرجاع غير عامة .
ولذا أود أن ما لا يقل عن تغييره إلى:
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، وربما يتم تخفيض مكرر إلى كونها كائن نوع ذلك فقط هذا العمل:
for (Object profile : m_PC) {
// do stuff
}
وهذه هي حالة زاوية غامضة جدا من الأدوية جافا.
إذا لم يكن كذلك، يرجى تقديم بعض مزيد من المعلومات حول ما يجري.
نصائح أخرى
أولا:
public class ProfileCollection implements Iterable<Profile> {
ثانيا:
return m_Profiles.get(m_ActiveProfile);