이전에 만난 문제가 있습니다. 그러나 여전히 그 이유는 알 수 없습니다.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 객체의 목록이라는 것을 지정 했으므로 여기서는 잘못된 것을 보지 못합니다.
아무도 도와 줄 수 있습니까?
피해
교훈을 배운 :
또한 당신이 더 많은 읽을 나에게하는 약간 다른 방법으로이 문제를 다시 작성할 수 있습니다 컴파일러 경고 "반복자는 ... 원시 타입을"무시하지 않는다; -) –
getCollection이 ArrayList 대신 List을 반환하도록하는 것이 더 나은 이유는 무엇입니까? 나는 이것이 인터페이스와 어떤 관련이 있는지 이해하지 못한다. (나는 여전히 자바를 배우고 있고 인터페이스의 사용과 기능을 이해하는 데 어려움을 겪고있다.) –
언젠가 당신이 당신의 클래스 여러 사용자가 동일한 사용자에게 액세스 할 수 있도록 스레드로부터 안전해야합니다. 아마도 ArrayList를 Vector로 변경하고 싶을 것입니다. List로 선언했다면, 생성자에서 초기화 된 곳에서 변경하면됩니다. ArrayList의 인스턴스로 전달하는 경우 사용 된 전체 응용 프로그램의 모든 부분을 변경해야합니다. – Affe