File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generic method add query" Watch "Generic method add query" New topic

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?

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>();
List<Long> listLong = new ArrayList<Long>();

<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);
not so useful
correct me if I am wrong :roll:
[ October 22, 2007: Message edited by: al nik ]

I agree. Here's the link:
subject: Generic method add query
It's not a secret anymore!