I'm having a problem that I have encountered before, but I still don't know why it happens. This is the code:
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;
}
}
The problem is with the getSeasonsCount method. the it.next() returns an Object instead of a Show object. As far as I know, this is a matter of generics, but I specified that the collection ArrayList is a list of Show objects, so I really don't see what is wrong here.
Can anyone help me?
Harm
Iterator it
will return only Object. Iterator<Show>
will give you the objects of type Show
. If you don't declare it that way, it won't be just assumed that the reference came from your List<Show>
Also for some unsolicited commentary :)
One should normally program to interfaces, getCollection should probably return List<Show>
rather than ArrayList<Show>
unless there is genuinely something relevant about the fact that it's an ArrayList
specifically.
You can also use the foreach construct rather than the iterator, which is generally preferable for readability etc.
for (Show show : getCollection()) {
amount += show.getSeasonCount();
}
I think you need Iterator<Show> it = getCollection().iterator();
in getSeasonsCount()
`
Why not use a Set instead of a list if you want to ensure that the entries are unique?
Also note you could rewrite this in a slightly different way, which to me is more readable:
public int getSeasonsCount(){
int amount = 0;
for (Show show : getCollection()) {
amount += show.getSeasonCount();
}
return amount;
}
精彩评论