File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic type-safety doubt

 
Kedar Pethe
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 537
Eclipse IDE Java Python
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Pritish Chakraborty
Ranch Hand
Posts: 91
C++ Firefox Browser Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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...
 
Kedar Pethe
Ranch Hand
Posts: 39
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic