aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in Generic collection Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in Generic collection" Watch "Doubt in Generic collection" New topic
Author

Doubt in Generic collection

rohit shekhar
Ranch Hand

Joined: Mar 05, 2010
Posts: 32



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

Joined: Apr 06, 2010
Posts: 4492
    
    8

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

Joined: Oct 13, 2009
Posts: 774
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,


Prithvi,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in Generic collection