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 itwill return only Object.Iterator<Show>will give you the objects of typeShow. If you don’t declare it that way, it won’t be just assumed that the reference came from yourList<Show>Also for some unsolicited commentary 🙂
One should normally program to interfaces, getCollection should probably return
List<Show>rather thanArrayList<Show>unless there is genuinely something relevant about the fact that it’s anArrayListspecifically.You can also use the foreach construct rather than the iterator, which is generally preferable for readability etc.