wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Confusion with Generics Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Confusion with Generics" Watch "Confusion with Generics" New topic
Author

Confusion with Generics

shameem Shek
Greenhorn

Joined: Aug 27, 2007
Posts: 9
Hi This is Shameem..
I have littlebit Confusion with Generics..

1. import java.util.*;
2. class TestGen
3. {
4.public static void main(String[] args)
5.{
6.Queue<Integer> q = new LinkedList<Integer>();
7.q.add(2342);
8.q.add(345);
9.q.add(455);
10.q.add(new String("ishmayel"));
11.q.add(new Double(324));
12.q.add(new StringBuilder("ishmayel"));
13.showAll(q);
14.}
15.public static void showAll(Queue q)
16.{
17. q.add(new Float("ishmayel"));
18. q.add(new Double(324));
19. q.add(new StringBuilder("ishmayel"));
20. while (!q.isEmpty())
21 System.out.print(q.remove()+ " ");
22.}
23. }

Why I am getting the compilation error at lines 10,11,12 but there is no compilation errors at line 17,18, 20 what is the reasion.

I think If there is any error at lines 10,11,12 that will be repeat at line 17,18,19 also but I am getting the errors at lines 10,11,12 only why..?
please any one can help me..
Thanks in advance..
Shammem.
Sheikh Sadiruddin
Greenhorn

Joined: Aug 10, 2007
Posts: 21
Hi shameem ,
Because your showAll(Queue q) method can take any type of Queue object. If you want to make it type safe , then use something like this showAll(Queue<yourType> q).
I think you have got it now.


SCJP 6 (80%) || SCWCD 5 (92%)
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
When you declare a Collection with type parameter, that means it can only hold objects of that type and its subtypes and nothing else, this check is done at compile time.

In the showAll(Queue q) you are declaring a Queue without type parameter i.e <type>, so you can add objects of various type. Note you will get warning here.
[ October 04, 2007: Message edited by: Ahmed Yehia ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Confusion with Generics