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

Doubt in Generic collection

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



Above code will add one String in an Integer type ArrayList. Why same logic gives here error in main if we will remove comment.
 
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You're mixing generic and non-generic code. That's only allowed so that generic code can interact with old (pre-Java 5) code that doesn't support generics - and the thing you have to accept in that case is that you lose type safety. As soon as you're in the insert() method the compiler can't help you, because you aren't using generics there.

But in the main method you've got a reference to a generic list. So any operations on that reference get the type-safety enforced.

The bottom line is, always avoid mixing generic and non-generic code unless you really have no choice in the matter.
 
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Rohit,

Combination of legacy and generics is allowed so that the older codes don't break. In the main method, you have declared a collection
which is type safe, it means it can only take Integer. That's why when you try to add an integer into a type safe list, it raises an except.
As soon as you will pass it to the legacy method, it will generate a WARNING, but as soon as the control enters the legacy method, it is a
legacy list, which doesn't have any concept of type saftey. As legacy lists, used to support heterogeneous collections, this one will also and will
let a String added to the list. So no exception in the legacy method.

HTH,
 
Too many men are afraid of being fools - Henry Ford. Foolish tiny ad:
We need your help - Coderanch server fundraiser
https://coderanch.com/wiki/782867/Coderanch-server-fundraiser
reply
    Bookmark Topic Watch Topic
  • New Topic