Iterableインターフェイスを実装するにはどうすればよいですか?

StackOverflow https://stackoverflow.com/questions/601658

  •  03-07-2019
  •  | 
  •  

質問

次のコードを指定すると、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は汎用インターフェースです。あなたが持っているかもしれない問題(あなたが実際にあなたが持っている問題を言っていません)は、タイプ引数を指定せずにジェネリックインターフェイス/クラスを使用すると、無関係なジェネリックタイプのタイプを消去できることですクラス内。この例はジェネリッククラスへの非ジェネリック参照は、非ジェネリック戻り型になります。

したがって、少なくとも次のように変更します。

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のtype引数がない場合、イテレータはObject型に縮小されるため、これだけが機能します:

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

これは、Javaジェネリックのかなりあいまいなケースです。

そうでない場合は、何が起こっているかについての情報を提供してください。

他のヒント

まず:

public class ProfileCollection implements Iterable<Profile> {

2番目:

return m_Profiles.get(m_ActiveProfile);
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top