Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Collections PRoblem

 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




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???
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mohit G Gupta
Ranch Hand
Posts: 634
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic