aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generic type-safety doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generic type-safety doubt" Watch "Generic type-safety doubt" New topic
Author

Generic type-safety doubt

Kedar Pethe
Ranch Hand

Joined: Jul 17, 2012
Posts: 39
The following code give no compiler error

But why does the listing below give compiler error?



Error-
symbol : method add(int)
location: interface java.util.List<java.lang.String>
l.add(55);
^





Whats the difference in handling of type-safe collection and legacy code between the first listing and the second one?
Nitish Bangera
Ranch Hand

Joined: Jul 15, 2009
Posts: 537

Generics are resolved at compile time. The references are always checked at compile time and at run time, the new keyword is executed to create an object. So when you define a generic list, you need to comply to that contract.


[ SCJP 6.0 - 90% ] , JSP, Servlets and Learning EJB.
Try out the programs using a TextEditor. Textpad - Java 6 api
Pritish Chakraborty
Ranch Hand

Joined: Jun 12, 2012
Posts: 91

Correct me if I'm wrong, but we know that on mixing generic and legacy code, the generic-type safety at compile time is lost.

There was never any safety at runtime anyway, due to type erasure.

Now if this is the case, if you assign an ArrayList<String> object to a legacy List container, I think the compiler relaxes type safety. That means safety is destroyed.

However, if you assign an ArrayList object to a List<String> container, type safety is enforced.

It is just as Nitish said...


OCJP 6
Kedar Pethe
Ranch Hand

Joined: Jul 17, 2012
Posts: 39
Nitish Bangera wrote:Generics are resolved at compile time. The references are always checked at compile time and at run time, the new keyword is executed to create an object. So when you define a generic list, you need to comply to that contract.

Ok.. understood.. We can also put it this way-
As new operator creates objects at runtime, and at runtime, type safety is not there, so the compiler doesn't bother to look generic argument after the new operator.
From this, we can infer that when you write
List<String> l =new ArrayList<String>();
The compiler checks the generic argument of the reference variable of List, and then checks the rest of the code to find whether anything non-String is added to the arraylist...


@ Nitish, Pritish: Thanks to both of you for clearing this!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic type-safety doubt