我有一个我以前遇到的问题,但我仍然不知道它为什么会发生。 这是代码:Java:ArrayList返回对象,而不是所需的类型
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()返回一个Object而不是一个Show对象。 据我所知,这是一个泛型的问题,但我指定收集ArrayList是一个Show对象的列表,所以我真的不明白这里有什么问题。
任何人都可以帮助我吗?
危害
教训:不要忽略编译器警告“的Iterator是一个原始类型...”; - ) – 2010-07-16 22:22:33
为什么最好让getCollection返回一个List而不是ArrayList?我真的不明白这与接口有什么关系..(我仍在学习Java,并且我不得不麻烦了解接口的使用和功能) –
2010-07-16 22:35:11
假设有一天你得到一个要求,你的类必须是线程安全的,以便多个用户可以访问同一个用户。您可能想要将ArrayList更改为Vector。如果你将它声明为List,你所要做的就是将它在构造函数中初始化的地方进行更改,并且它在任何地方都是固定的。如果您将它作为ArrayList的实例传递,则必须在整个应用程序中的任何位置进行更改。 – Affe 2010-07-16 22:41:17