• 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

Regarding Generics usage in jdk1.5

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

I am trying to implement generics concept in jdk1.5.

Please have a glance at the below code:
import java.util.*;
class GenericsDemoo
{
public static void main(String args[])
{
ArrayList<String> al = new ArrayList<String>();
al.add("Naresh");
al.add("Kumar");
al.add("Sunil");
al.add("Santosh");
Iterator it = al.iterator();
while(it.hasNext())
{
String str=it.next();
System.out.println(str.substring(0,2));
}
}
}

When i tried to compile the above code i am facing a compile time error with the message.

GenericsDemoo.java:14: incompatible types
found : java.lang.Object
required : java.lang.String
String str=it.next();

1 error


MyQuestion:
The only concept behind generics is we need not do the typecasting for the objects retrieved from the collection.Isn't it? or did i understood generics concept wrongly.please clarify me.

Thanks in advance.
 
Ranch Hand
Posts: 166
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

the next() will return the next object in the collection which is of type "Object". so there is a type incompatability.

we need to use generics syntax to create the Iterator.

in your case you should the code to

Iterator<String> it = al.iterator();

so that there is no need of type cast.

Hope this help you.

Srividhya
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic