• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Devaka Cooray
  • Ron McLeod
  • Jeanne Boyarsky
Sheriffs:
  • Liutauras Vilda
  • paul wheaton
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Stephan van Hulst
  • Piet Souris
  • Carey Brown
  • Tim Holloway
Bartenders:
  • Martijn Verburg
  • Frits Walraven
  • Himai Minh

Confusion with Generics

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Greenhorn
Posts: 21
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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 ]
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic