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);

}

}

[2768 byte] By [dukhaa] at [2007-11-27 9:28:16]
# 1

class GenGen <K extends Shape> {

private List<K> dataList;

private K dataObject;

public K getDataObject() {

return dataObject;

}

public List<K> getCollection() {

if(dataList==null){

//refreshDataCollection();

}

return dataList;

}

public void create(){

getCollection().add(getDataObject());

}

protected void setCollection(Collection<K> m) {

dataList = new ArrayList<K>(m) ;

for(Shape t: dataList){

// t.setStatus(HasCriteria.Status.SAVED);

}

}

public void refreshDataCollection(String jpaQL, List modelParameters){

List rl = null;

setCollection(rl);

}

}

Note that in that final setCollection, you'll get an unchecked conversion warning, if you haven't turned them off.

jverda at 2007-7-12 22:32:39 > top of Java-index,Core,Core APIs...
# 2
Many thanks for the clear example. Naturally, it worked. I also now understand how to do generic typing much better.Thanx again.Mark
dukhaa at 2007-7-12 22:32:39 > top of Java-index,Core,Core APIs...