| Author |
Generic method add query
|
ahmed yehia
Ranch Hand
Joined: Apr 22, 2006
Posts: 424
|
|
I m testing this generic method, it works well but when add something to the List it reports an error.. What is the reason? Thanks
|
 |
al nik
Ranch Hand
Joined: Oct 18, 2007
Posts: 60
|
|
public static <E extends Number> void add(List<E> list) { says "I accept a list of type E that 'extends Number' so you can call this method with something like List<Integer> listInt = new ArrayList<Integer>(); add(listInt); or List<Long> listLong = new ArrayList<Long>(); add(listLong); <E extends Number> don't let you to put what you want in the List<E> simply because the compiler has no way to resolve what's the type at compile time and you can corrupt your List. Think about if the add() method add a new Float() to your type safe 'listInt'... that's no good you can add only an E obj.. something like this E e = list.get(0); list.add(e); not so useful correct me if I am wrong :roll: [ October 22, 2007: Message edited by: al nik ]
|
SCJP5 - SCWCD5 - SCBCD5
|
 |
 |
|
|
subject: Generic method add query
|
|
|