• Post Reply Bookmark Topic Watch Topic
  • New Topic

List casting  RSS feed

 
Philip Pomario
Ranch Hand
Posts: 113
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why is the following legal...
Number number = new Float(10f);

Whereas this is not...
List<Number> listNumber = new ArrayList<Float>();

Thanks!
 
jishnu dasgupta
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I think it is because Number is an abstract class.Me not sure though.
 
Buddhika Mawella
Ranch Hand
Posts: 40
Eclipse IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I cant agree with jishnu's answer.Normally you can assign a subtype object to its super type reference. But in java generics it’s not applicable. By putting <Number> after List reference, you are telling that reference listNumber can hold lists only with the same generic type. Write below code and try to compile. That compiles without any problem.

That's how java generics behave.Refer 7th chapter, ‘Generics and Collections’ in 'SCJP Sun Certified Programmer for Java 5 Study Guide' book witch was written by Kathey Sierra to get a better understanding about java generics.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The key point is:
- Float IS-A Number.
- List<Float> IS-NOT-A List<Number>

The reason for this is that it would destroy the type safety. Like this:
Line 2 is adding an Integer to a List<Number> reference. The compiler has to allow that. But that means we've added an Integer to an ArrayList<Float>. So the compiler won't allow the assignment in the first place.
 
jishnu dasgupta
Ranch Hand
Posts: 103
Eclipse IDE Java Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah i was wrong, just checked with generics, if you specify a particular type, then you cant use its sub type or its super type!!! sorry for the wrong post!!!
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No. It is because Float extends Number, but List<Float> doesn't extend List<Number>. Go through the Java™ Tutorials and look for "generics" and this is one of the sections you find. It explains that a Cage<Lion> and a Cage<Butterfly> don't extend Cage<Animal>. It is exactly the same problem here. Read that, and see whether it helps you. If not, ask again.
 
Don't get me started about those stupid light bulbs.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!