Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic method add query

 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Posts: 60
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic