How do you add an object to a collection typed witha wildcard?
Hi All,
I want to add an object to a collection typed with a wildcard but I can't figure out how to do it.
I've been thru the generics tutorial again and I now understand that I can't do exactly what I want to and why. However I don't know how to do it right. I copy some code below to show the problem:
private List<?extends HasCriteria> dataList;
private HasCriteria dataObject;
public HasCriteria getDataObject(){
return dataObject;
}
public List<?extends HasCriteria> getCollection(){
if(dataList==null){
refreshDataCollection();
}
return dataList;
}
/*I want to be able to do theadd()
below but the generics tutorial assures me, as does the compiler, that I can't. So how do I get an object into the collection?*/
publicvoid create(){
...........
getCollection().add(getDataObject());
}
/*I don't understand why I can do this setCollection() call below as the compiler has no idea that the resultList is of type HasCriteria, however I accept that it is ok with this*/
protected <Textends HasCriteria>void setCollection(Collection<T> m){
dataList =new ArrayList<T>(m) ;
for(HasCriteria t: dataList){
t.setStatus(HasCriteria.Status.SAVED);
}
}
publicvoid refreshDataCollection(String jpaQL, List modelParameters){
Query q = em.createQuery(jpaQL);
.............
List rl = q.getResultList();
if(rl !=null){
setCollection(rl);
setModelQuery(jpaQL, modelParameters);
}
}

