S
Safalra
Consider the following code:
Vector<String> s=new Vector<String>(10);
Vector o=s;
o.add(new Object());
Object p=s.get(0);
Obviously this gives an unchecked warning about the second line.
Because of type erasure the third line doesn't cause a run-time
exception either. What surprises me is that the fourth line doesn't
cause a class cast exception, despite accessing the Vector through s. I
presume internally type erasure turns it into:
Object p=(Object)(String)s.get(0);
Which the compiler simplifies to:
Object p=s.get(0);
Is my understanding of this correct, and do people here regard this a
bug in the compiler, or just another consequence of allowing unchecked
exceptions in your code?
(I discovered this while writing an article for a friend of mine who
isn't a fan of Java - you can read it at
http://www.safalra.com/programming/java/wrongerasure/ but remember that
I *do* actually like Java in general, I just dislike certain features.)
Vector<String> s=new Vector<String>(10);
Vector o=s;
o.add(new Object());
Object p=s.get(0);
Obviously this gives an unchecked warning about the second line.
Because of type erasure the third line doesn't cause a run-time
exception either. What surprises me is that the fourth line doesn't
cause a class cast exception, despite accessing the Vector through s. I
presume internally type erasure turns it into:
Object p=(Object)(String)s.get(0);
Which the compiler simplifies to:
Object p=s.get(0);
Is my understanding of this correct, and do people here regard this a
bug in the compiler, or just another consequence of allowing unchecked
exceptions in your code?
(I discovered this while writing an article for a friend of mine who
isn't a fan of Java - you can read it at
http://www.safalra.com/programming/java/wrongerasure/ but remember that
I *do* actually like Java in general, I just dislike certain features.)