• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Collections PRoblem

 
Ranch Hand
Posts: 634
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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???
 
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Eclipse IDE Chrome Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
Bartender
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic