2010-07-16 3 views
0

이전에 만난 문제가 있습니다. 그러나 여전히 그 이유는 알 수 없습니다.Java : ArrayList가 원하는 유형 대신 Object를 반환합니다.

package Program; 

import java.util.ArrayList; 
import java.util.Iterator; 

/** 
* This class will hold the full collection of the user. 
* 
* @author Harm De Weirdt 
*/ 
public class ShowManager { 

    /** 
    * The collection of shows of this user. 
    */ 
    private ArrayList<Show> collection; 

    private static final ShowManager INSTANCE = new ShowManager(); 

    // Private constructor prevents instantiation from other classes 
    private ShowManager() { 
     collection = new ArrayList<Show>(); 
    } 

    public static ShowManager getInstance() { 
     return INSTANCE; 
    } 

    private ArrayList<Show> getCollection() { 
     return collection; 
    } 

    /** 
    * Add a new Show to the collection 
    * 
    * @param newShow 
    *  The show to be added 
    * @post if <newShow> was not null and the collection didn't already contain 
    *  <newShow>, <newShow> was added to the collection 
    *  |getCollection().contains(<newShow>) 
    */ 
    public void addShow(Show newShow){ 
     if(newShow != null && !getCollection().contains(newShow)){ 
      getCollection().add(newShow); 
     } 
    } 

    /** 
    * Gives the amount of shows this user has in his collection. 
    * 
    * @return the size of <collection>. 
    */ 
    public int getShowCount(){ 
     return getCollection().size(); 
    } 

    public int getSeasonsCount(){ 
     Iterator it = getCollection().iterator(); 
     int amount = 0; 
     while(it.hasNext()){ 
      amount += it.next().getSeasonCount(); 
     } 
     return amount; 
    } 
} 

문제는 getSeasonsCount의 방법입니다 : 이 코드입니다. it.next()는 Show 객체 대신 Object를 반환합니다. 제가 아는 한, 이것은 generics의 문제입니다. ArrayList 컬렉션이 Show 객체의 목록이라는 것을 지정 했으므로 여기서는 잘못된 것을 보지 못합니다.

아무도 도와 줄 수 있습니까?

피해

답변

11

Iterator it는 객체를 반환합니다. Iterator<Show>Show 유형의 개체를 제공합니다. 당신이 그런 식으로 선언하지 않으면, 단지 참조 일부 원치 않는 논평 : 는 하나 일반적으로 인터페이스 프로그램, getCollection 아마 List<Show>를 반환하는 대신해야한다 위해 또한 당신의 List<Show>

에서 온 것으로 간주되지 않습니다 ArrayList<Show>입니다. 실제로는 ArrayList이라는 사실과 관련이 있습니다.

또한 등 가독성 내가 대신 설정 사용하지 왜 getSeasonsCount() `

+1

교훈을 배운 :

또한 당신이 더 많은 읽을 나에게하는 약간 다른 방법으로이 문제를 다시 작성할 수 있습니다 컴파일러 경고 "반복자는 ... 원시 타입을"무시하지 않는다; -) –

+0

getCollection이 ArrayList 대신 List 을 반환하도록하는 것이 더 나은 이유는 무엇입니까? 나는 이것이 인터페이스와 어떤 관련이 있는지 이해하지 못한다. (나는 여전히 자바를 배우고 있고 인터페이스의 사용과 기능을 이해하는 데 어려움을 겪고있다.) –

+2

언젠가 당신이 당신의 클래스 여러 사용자가 동일한 사용자에게 액세스 할 수 있도록 스레드로부터 안전해야합니다. 아마도 ArrayList를 Vector로 변경하고 싶을 것입니다. List로 선언했다면, 생성자에서 초기화 된 곳에서 변경하면됩니다. ArrayList의 인스턴스로 전달하는 경우 사용 된 전체 응용 프로그램의 모든 부분을 변경해야합니다. – Affe

2

에 대한 일반적으로 바람직하다 반복자, 대신 foreach는 구문을 사용할 수 있습니다 항목이 고유한지 확인하려면 목록을 선택하십시오.

public int getSeasonsCount(){ 
    int amount = 0; 
    for (Show show : getCollection()) { 
     amount += show.getSeasonCount(); 
    } 
    return amount; 
} 
2

Iterator<Show> it = getCollection().iterator(); 필요하다고 생각

for (Show show : getCollection()) { 
    amount += show.getSeasonCount(); 
} 
+0

대신 집합을 사용하여, 존재하지 않았다는 것을 알게 될 것입니다 :) –

+0

또한 int i 루프의 표준보다 성능이 좋지 않습니다. – Woot4Moo

+0

전체 it.hasNext()가 성능이 나 빠졌음을 의미합니까? 쓰기 (int i = 0, i

관련 문제