aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generic method add query Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generic method add query" Watch "Generic method add query" New topic
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic method add query