• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in Generic collection

 
rohit shekhar
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • 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.
 
Matthew Brown
Bartender
Posts: 4566
8
  • Mark post as helpful
  • send pies
  • 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.
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • 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,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic