This week's book giveaway is in the OO, Patterns, UML and Refactoring forum.
We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line!
See this thread for details.
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
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’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com
 
subject: Generic method add query
 
It's not a secret anymore!