Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics doubt?

 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Someone tell me why line 2 compiles file ,but line1 does not-
 
Henry Wong
author
Marshal
Pie
Posts: 20998
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Generics needs to be backward compatible -- so line 2 is allowed. It does however, generate warning errors. And the assignment is not recommended.

Henry
 
M Srilatha
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Line 1 doesnt compile because list1 is declared as of type List<Object>.
So list1 can be assigned only to a List or subtype of List having Object as Generic parameter.

Here in Line1, list1 is being assigned to an object of ArrayList<Integer> which is not legal. Thats why the code doesnt compile.

Hope this is clear!
 
Ankit Garg
Sheriff
Posts: 9510
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If line 1 would have compiled, then it would have removed the type safety that generics provide.

Suppose the following line would have compiled
ArrayList<Object> l = new ArrayList<Integer>();

then you could have done this
l.add(new String("hello"));

as l is of type Object and String is a sub-type of Object. Then look at the following code



So as you can see that in that case, there would be a run-time exception. This is what we are trying to avoid using Generics...
 
Satya Maheshwari
Ranch Hand
Posts: 368
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


This like assuming a basket of apples as a basket of fruits. Although intutively correct, this is going to break if you try to put a mango in the apple basket thinking it was a fruit basket.
 
Pranav Bhatt
Ranch Hand
Posts: 284
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ha ha Satya Nice example
 
Ashok Pradhan
Ranch Hand
Posts: 180
Eclipse IDE Firefox Browser Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
OK,Thanks to all
 
Ananth Chellathurai
Ranch Hand
Posts: 349
Eclipse IDE Hibernate Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice Example Satya.

Ananth Chellathurai
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic