File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics 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 "Generics" Watch "Generics" New topic
Author

Generics

Abhishek Reddy
Ranch Hand

Joined: Mar 28, 2006
Posts: 259
public static void main(String[] args)
{
Queue<String> q=new LinkedList<String>();
q.add("Abhishek");
q.add("Duncan");
showAll(q);
}
public static void showAll(Queue q)
{
q.add(new Integer(42));
while(!q.isEmpty())
System.out.print(q.remove()+"");
}

here is my doubt I declared 'q' is of type Queue which is generic type and can hold only String values, whereas in showAll() wch takes queue as parameter, iam trying to enter interger objects into the queue. Is it possible if yes explain me..


Abhishek
Gowher Naik
Ranch Hand

Joined: Feb 07, 2005
Posts: 643
in method showall q is not generic
if you want to make it generic use Queue<String> q
as shown below.
Neelesh Bodas
Ranch Hand

Joined: Jul 20, 2006
Posts: 107
Originally posted by Abhishek Reddy Chepyala:
here is my doubt I declared 'q' is of type Queue which is generic type and can hold only String values, whereas in showAll() wch takes queue as parameter, iam trying to enter interger objects into the queue. Is it possible if yes explain me..


Yes, this works, since the Generic code can be freely mixed with corresponding non-generic code. Howeverif you try to treat the Integer as a String later on [assuming that you passed a Queue<String> ;] , you would get a ClassCastException.
[ August 07, 2006: Message edited by: Neelesh Bodas ]
Burkhard Hassel
Ranch Hand

Joined: Aug 25, 2006
Posts: 1274
But the compiler will warn you in line


The compiler warning occurs because changing members of generic classes that are used non-generically is not type safe.
showAll takes raw type Queues as parameter, and these operate on type Object, so you can add anything to it (Integer, Strings, JButtons...).
The warning makes sense here, as your code would produce a Class Cast Exception at runtime. But also if you used add("a string"); the warning would have been there.
If you used showAll generically <String>, adding an Integer would shift from an exception at runtime to a compile time error. So Generics helps you to see your programming mistakes earlier - but only if you use generics.

Yours,
Bu.


all events occur in real time
 
Don't get me started about those stupid light bulbs.
 
subject: Generics