I understand why we could not add an element to List<? extends Number>. It is illegal to do:

That's why I do (List<Number>)childList. What I don't understand why it doesn't throw ClassCastException when parentList.add(3.14). Because the underlying list is a ArrayList<Integer> and 3.14 is not a integer, when Java tries to implicitly convert 3.14 to integer, is it a ClassCastException?

I understand why we could not add an element to List<? extends Number>. It is illegal to do:

So you understand that adding is "illegal"? But why is it "illegal"? Because it can violate the type safety !!

That's why I do (List<Number>)childList. What I don't understand why it doesn't throw ClassCastException when parentList.add(3.14). Because the underlying list is a ArrayList<Integer> and 3.14 is not a integer, when Java tries to implicitly convert 3.14 to integer, is it a ClassCastException?

Generics is only at compile time. ClassCastExceptions happen at runtime, when the generic type has already been erased.

IOWs, if you use generics, try your best to *not* cast anything... you need to let the generic do it's work.

Henry

L Yan
Greenhorn

Joined: Apr 25, 2006
Posts: 18

posted Mar 12, 2009 11:12:36

0

Henry Wong wrote: IOWs, if you use generics, try your best to *not* cast anything... you need to let the generic do it's work.
Henry

I definitely agree with you. I don't really want to do cast List<? extends Number> to List<Number>. But it doesn't seem that I have other choice. I have this set of API:

SomeFactory class is responsible to create a instance of BasePOJO's subclass and populate the data using the template. The ABC class is responsible to return an appropriate instance of SomeFactory according to the pojo Class passed in. And XYZ class actually uses the SomeFactory to create an instance of BasePOJO's subclass. For example, BasePOJO could be Animal. Then we could have SomeFactory<Cat> and SomeFactory<Dog>. If we do XYZ.generate(Cat cat), it would retrieve SomeFactory<Cat> and use SomeFactory<Cat>.createByTemplate(Cat catTemplate) to get a Cat instance.

That's fine..... But you are complaining that generics can't detect the type correctly, when you are forcing the type.

And BTW, if you are getting "errors" because the type is wrong -- after you forced the type -- doesn't that tell you that generics was right in not allowing the operation?

Henry

L Yan
Greenhorn

Joined: Apr 25, 2006
Posts: 18

posted Mar 12, 2009 15:28:51

0

Henry Wong wrote:

And BTW, if you are getting "errors" because the type is wrong -- after you forced the type -- doesn't that tell you that generics was right in not allowing the operation?

Henry

I agree with you that it's not because generic is wrong that I have to cast the a generic type to a non-generic type. I guess the question in my previous thread is how to update the design to use the generic correctly and avoid any manual casting. Thank you very much for your reply.