Why does Java ArrayList use per-element casting instead of per-array casting?

Posted by user1111929 on Stack Overflow See other posts from Stack Overflow or by user1111929
Published on 2012-09-11T08:50:52Z Indexed on 2012/09/11 9:38 UTC
Read the original article Hit count: 139

Filed under:
|
|

What happens inside Java's ArrayList<T> (and probably many other classes) is that there is an internal Object[] array = new Object[n];, to which T Objects are written. Whenever an element is read from it, a cast return (T) array[i]; is done. So, a cast on every single read.

I wonder why this is done. To me, it seems like they're just doing unnecessary casts. Wouldn't it be more logical and also slightly faster to just create a T[] array = (T[]) new Object[n]; and then just return array[i]; without cast? This is only one cast per array creation, which is usually far less than the number of reads.

Why is their method to be preferred? I fail to see why my idea isn't strictly better?

© Stack Overflow or respective owner

Related posts about java

Related posts about casting