Re: Will the new Generics mechanism still use runtime casting?

From: Dobromir Gaydarov (dobri_at_vif.com)
Date: 10/07/03


Date: Mon, 6 Oct 2003 22:24:41 -0400

I have actually tried and the program below works just fine.
Apart from the warning for

list.add( new Object() );

as promissed by the spec the program compiles well and executes normally to
the end.

The get a failure you have to try assignment like

Frame f = frameList.get( 1 );

and then you get ClassCastException at runtime.

Regards,
Dobromir

"Phillip Lord" <p.lord@russet.org.uk> wrote in message
news:vfwubqmkm2.fsf@rpc71.cs.man.ac.uk...
> >>>>> "xarax" == xarax <xarax@email.com> writes:
>
> xarax> "Skippy" <s.balk@hccnet.n0spam.nl> wrote in message
> xarax> news:<blaf8a$fpi$1@news.hccnet.nl>...
> >> > With Generics, there is no longer a need to insert an explicit
> >> > cast. BUT, underneath the hood in the implementation, is there
> >> > a still a cast being performed at runtime in a statement like
> >> > the one above?
> >>
> >> Yep, generics are there to inform the compiler and ease the
> >> class-casting pain, but the bytecode output is the same.
>
> xarax> A properly implemented JVM can perform a cast or instanceof
> xarax> test in constant time, regardless of the complexity of the
> xarax> inheritance graph.
>
>
> Actually I don't think that it can, unless it pre-calculates a
> transitive closure. Which it can't do in constant time.
>
> xarax> Don't worry about it. Computers exist for the convenience of
> xarax> people, not vice versa. The big benefit of Generics is that
> xarax> the compiler knows for certain that the cast will work or not
> xarax> work. If the cast won't work, then you see a compile error
> xarax> and can fix your code sooner than waiting for a runtime
> xarax> exception.
>
>
> No. The "cast" can fail. And if it does you will get a
> CastClassException where no Cast exists in code, only in byte code.
>
> So for instance....
>
> // generics working well...
> List<Frame> frameList = new List<Frame>();
> frameList.add( new Frame() );
> Frame frame = frameList.get( 0 )
>
>
> // this is an up cast. List<Frame> is a subtype of List...
> List list = (List)frameList;
> list.add( new Object() );
> Object object = list.get( 1 );
>
> //and this bit fails
> frameList.get( 1 );
>
>
> So in fact while generics mean that you don't have to put casts where
> you used to, but they offer you few guarantees. At best I think they
> should be considered something like more auto-boxing...that is more
> syntactic sugar, than stronger type checking.
>
> Phil