Win a copy of Machine Learning Systems: Designs that scale this week in the Scala forum
or Xamarin in Action: Creating native cross-platform mobile apps in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Generics  RSS feed

 
Ranch Hand
Posts: 105
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
import java.util.*;
class exp{

public static void main(String ar[])
{
List <? extends Number>l1=null;
List<? super Number> l2=null;
l2=l1;
}
}

Why does this code not work?
 
Marshal
Posts: 5923
875
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to JavaRanch.
Please UseCodeTags when you post a code at JavaRanch. Please edit your post and add code tags.
Not related to Servlets - Moving to BG...
 
Devaka Cooray
Marshal
Posts: 5923
875
Chrome Eclipse IDE Google App Engine IntelliJ IDE jQuery Postgres Database Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is because the generics-scope of l1 and l2 do not match.
Please read GenericsSuperAndExtends to understand the scope of 'extends' and 'super'.
 
Ranch Hand
Posts: 423
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider what would be if this assignment was legal:

In this code in line 6 we get Object from the list that is declared that can contain only Numbers.
This breaks program with ClassCastException.
To avoid situation like this, compiler prevents assignment in line 04.
 
Squanch that. And squanch this tiny ad:
Rocket Oven Kickstarter - from the trailboss
https://coderanch.com/t/695773/Rocket-Oven-Kickstarter-trailboss
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!