Win a copy of Mastering Corda: Blockchain for Java Developers this week in the Cloud/Virtualization forum!
  • 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Bear Bibeault
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Jj Roberts
  • Carey Brown
Bartenders:
  • salvin francis
  • Frits Walraven
  • Piet Souris

Confusion with Generics

 
Greenhorn
Posts: 9
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • 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 ]
 
"How many licks ..." - I think all of this dog's research starts with these words. Tasty tiny ad:
Building a Better World in your Backyard by Paul Wheaton and Shawn Klassen-Koop
https://coderanch.com/wiki/718759/books/Building-World-Backyard-Paul-Wheaton
reply
    Bookmark Topic Watch Topic
  • New Topic