wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Collections PRoblem 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 "Collections PRoblem" Watch "Collections PRoblem" New topic
Author

Collections PRoblem

Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634





a)

inconvertible types
found : java.util.ArrayList<A>
required: java.util.ArrayList<B>
ArrayList<B> three=(ArrayList<B>)one;

i know why the above compile time error come as this is not allowed in generics


b)

here we are casting from two ArrayList that can accept anything to ArrayList that accept objects of type B
shouldn't there be compile-time error.i mean object and ArrayList<B>


while in this case,classcastexception occurs

Exception:
java.lang.ClassCastException: A cannot be cast to B

why such difference in case of collection and normal classes???

OCPJP 6.0 93%
OCPJWCD 5.0 98%
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

B: That's why you're getting a big warning.

It's not different. Try this:


It throws an exception because the casting only happens when needed.


"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
Mohit G Gupta
Ranch Hand

Joined: May 18, 2010
Posts: 634

Wouter Oet
It throws an exception because the casting only happens when needed.



Why isn't it shows compile time error

how is casting from OBject to B allowed here???


isn't it similar to



casting from A to B
Wouter Oet
Saloon Keeper

Joined: Oct 25, 2008
Posts: 2700

It doesn't cause a compiler error because it is valid to cast a non-generic ArrayList to a generic one. But it's dangerous thus the warning.
It's illegal to cast an generic ArrayList to another generic ArrayList.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Collections PRoblem