• 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

generic doubt

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



p

Both code are same except only one(in bold) line I have added into 2nd code.
Why the first code compiles? Why in print statement it takes list.get(0) without cast?
But if I add String s=list.get(0), it gives me compiler error. Because "List list" is a non-generic, so the things comes out are Object type.

Now my question is , who is doing cast in print statement? Or I am missing something? can anyone please explain?
 
Ranch Hand
Posts: 329
Oracle Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Because list is not typed, and it is what is commonly known as a raw type. I.e: you are not using generics.

Your code is completely equivalent to the following pre-5.0 code:


In line:
List list=new ArrayList<String>();
you are loosing type information by assigning the generic ArrayList<String> to a raw type (List)

You need to modify your code in the following way:
 
Author
Posts: 84
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

who is doing cast in print statement?


No one is doing a cast - PrintStream (which System.out is an instance of) contains both a void print(Object obj) as well as a void print(String s) method. So in the version of the code that compiles, it's calling the print(Object) version of the overloaded method. Hope that helps!
 
dolly shah
Ranch Hand
Posts: 383
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Peter.
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic