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


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics doubt?" Watch "Generics doubt?" New topic
Author

Generics doubt?

Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

Someone tell me why line 2 compiles file ,but line1 does not-
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18116
    
  39

Generics needs to be backward compatible -- so line 2 is allowed. It does however, generate warning errors. And the assignment is not recommended.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
M Srilatha
Ranch Hand

Joined: Aug 27, 2008
Posts: 137
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!


Thanks,<br />Srilatha M
Ankit Garg
Sheriff

Joined: Aug 03, 2008
Posts: 9280
    
  17

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...


SCJP 6 | SCWCD 5 | Javaranch SCJP FAQ | SCWCD Links
Satya Maheshwari
Ranch Hand

Joined: Jan 01, 2007
Posts: 368


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.


Thanks and Regards
Pranav Bhatt
Ranch Hand

Joined: Mar 20, 2006
Posts: 284
Ha ha Satya Nice example
Ashok Pradhan
Ranch Hand

Joined: Dec 17, 2007
Posts: 180

OK,Thanks to all
Ananth Chellathurai
Ranch Hand

Joined: Nov 21, 2007
Posts: 349

Nice Example Satya.

Ananth Chellathurai


Ananth Chellathurai [Walk on software]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics doubt?
 
Similar Threads
Please explain me
How do I read this?
Question about Generics in Arrays
Generics Doubt
construct ArrayList from int[]