I have a List which is declared like this :
List extends Number> foo3 = new ArrayList();
I tried to add 3 to foo3.
You can fudge it by creating a reference to the List with a different type.
(These are the "unsafe casts" mentioned by sepp2k.)
List extends Number> list = new ArrayList();
// This will not compile
//list.add(100);
// WORKS, BUT NOT IDEAL
List untypedList = (List)list;
// It will let you add a number
untypedList.add(200);
// But it will also let you add a String! BAD!
untypedList.add("foo");
// YOU PROBABLY WANT THIS
// This is safer, because it will (partially) check the type of anything you add
List superclassedList = (List)(List>)list;
// It will let you add an integer
superclassedList.add(200);
// It won't let you add a String
//superclassedList.add("foo");
// But it will let you add a Float, which isn't really correct
superclassedList.add(3.141);
// ********************
// So you are responsible for ensuring you only add/set Integers when you have
// been given an ArrayList
// ********************
// EVEN BETTER
// If you can, if you know the type, then use List instead of List
List trulyclassedList = (List)(List>)list;
// That will prevent you from adding a Float
//trulyclassedList.add(3.141);
System.out.println("list: " + list);
Because untypedList
, superclassedList
and trulyclassedList
are just references to list
, you will still be adding elements to the original ArrayList.
You don't actually need to use (List>)
in the example above, but you might need it in your code, depending on the type of list
you were given.
Note that using ?
will give you compiler warnings, until you put this above your function:
@SuppressWarnings("unchecked")