2010-07-16 84 views
0

我有一个我以前遇到的问题,但我仍然不知道它为什么会发生。 这是代码: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对象的列表,所以我真的不明白这里有什么问题。

任何人都可以帮助我吗?

危害

回答

11

Iterator it将返回唯一对象。 Iterator<Show>会给你Show类型的对象。如果你不声明这样的说法,它不会只是假设基准从List<Show>

也来了一些不请自来的评论:) 每个人都应该正常程序接口,getCollection或许应该回到List<Show>,而不是除非真的有关于它的具体事实是ArrayList

您还可以使用foreach构造,而不是迭代器,这是通常优选可读性等

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

教训:不要忽略编译器警告“的Iterator是一个原始类型...”; - ) – 2010-07-16 22:22:33

+0

为什么最好让getCollection返回一个List 而不是ArrayList?我真的不明白这与接口有什么关系..(我仍在学习Java,并且我不得不麻烦了解接口的使用和功能) – 2010-07-16 22:35:11

+2

假设有一天你得到一个要求,你的类必须是线程安全的,以便多个用户可以访问同一个用户。您可能想要将ArrayList更改为Vector。如果你将它声明为List,你所要做的就是将它在构造函数中初始化的地方进行更改,并且它在任何地方都是固定的。如果您将它作为ArrayList的实例传递,则必须在整个应用程序中的任何位置进行更改。 – Affe 2010-07-16 22:41:17

2

我认为你需要Iterator<Show> it = getCollection().iterator();getSeasonsCount() `

2

为什么不使用,而不是设置列表如果你想确保条目是唯一的?

另外请注意,你可以在一个稍微不同的方式改写这一点,这对我来说是更具可读性:

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

我会考虑使用一个Set来代替,不知道它是否存在:) – 2010-07-16 22:33:30

+0

它也比int int的标准有更差的性能循环 – Woot4Moo 2010-07-16 22:33:44

+0

你的意思是说整个it.hasNext()的性能差,那么当我想写for(int i = 0,i 2010-07-16 22:39:30