• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Generics

 
Ranch Hand
Posts: 167
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Gives compiler error of incompatible types (Object to Integer)

What is significance of puting <Type> on Left hand side and Right hand side.? Is it mandatory for both sides to have?

 
Rancher
Posts: 43081
77
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to declare "Set<Integer>" instead of just "Set". Otherwise the for loop doesn't know that it can assume integers. So, yes, you need to put <Type> on both sides in a declaration.
 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here you are trying to assign a type safe class to a type unsafe class. The type safe generics accepts strictly the same type of objects as declared in the defination of the class so here only objects of Integer type is acceptable.

Also declaring the type in left or right side affects it's behaviour.

As the following code will compile but will give warning at compile time saying you are doing unsafe operation because we are trying to assign type safe generics to type unsafe class and after Java 5.0 it will be flaged as warning.

Set s=new HashSet<Integer>();
s.add(6);
s.add(5);
for(Object i:s){System.out.println(i);

But when you declare a collection class to be type safe as follows,

Set<Integer> s=new HashSet<Integer>();
s.add(6);
s.add(5);
for(Integer i:s){System.out.println(i);

it will compile successfully and allow only Integers to be added to s. If you try to add objects of other type it will give compiler error.
reply
    Bookmark Topic Watch Topic
  • New Topic