Difficulty with Generic Wildcarding

I don't seem to be able to have a List which can contain two different kinds of objects (List would either be all Object A or all Object B, never a combination of both). On the below code, the compiler (Eclipse...) gives the error:

The method add(capture-of ?) in the type List<capture-of ?> is not applicable for the arguments

(Integer)

List<?> versions =null;

try{//Try and catch here still, but I changed object types such that it is useless

ArrayList<String> test =new ArrayList<String>();

test.add("test");

versions = test;//works

}catch ( Exception e ){

Integer test = 0;

versions =new ArrayList<Integer>();

versions.add(test);// compiler error

}

If I don't use the generic parameterization, the code works fine and the compiler just give me a warning. Any ideas?

[1284 byte] By [frutcheya] at [2007-10-3 5:23:34]
# 1

Generics is specifically designed to prevent you doing this kind of nastiness. And it's working great! :-)

I could explain the problem if you like...

But the fix is either:

a) Don't do this. It's nasty and will be source of bugs. Use different lists for the different types.

b) Change your list to List<Object>. This list will be able to hold any subclass of object and will work just like it always used to.

dannyyatesa at 2007-7-14 23:30:40 > top of Java-index,Core,Core APIs...
# 2

If you would have done the same in try and catch, both would have either compiled or failed. The difference:

- In try, you create test as List of String and add a value to that list. Finally, you assign it to versions.

- In catch, you create a List of Integer that you assign to versions. Now, versions is a List of unknown type, so you cannot add an Integer.

stefan.schulza at 2007-7-14 23:30:40 > top of Java-index,Core,Core APIs...