opinali at gmail.com
Wed Jul 14 15:57:25 PDT 2010
2010/7/14 John Nilsson <john at milsson.nu>
> On Wed, Jul 14, 2010 at 12:16 AM, Nathan Bryant
> <nathan.bryant at linkshare.com> wrote:
> > John,
> > If you mean what I think you mean, that seems to result in a generics
> that is useful only for interface definition. Either it's not possible to
> > foo = new ArrayList<int>()
> > Or doing so results in autoboxing to Integer, unbeknownst to the user,
> which is a serious violation of the principle of least surprise.
> Or there is some clever hacks in ArrayList to handle the issue. An
> empty array is just empty, so no need to have any specific array-type.
> If the first element added is an int or Integer you could
> optimistically assume that all input will be ints and thus allocate an
> int, should that assumption turnout to be wrong, in later adds you
> allocate an Object.
This would create some extra effort - instanceof, typecast and branches - in
many critical methods like add(), get() etc. For collections of primitives,
this would be much better than the cost of boxing; but for collections of
reference types, we would make existing code (close to 100% of current code)
slower, even if just a bit... which is not acceptable, breaks the "first, do
no harm" principle. (Collections are critical enough that any 1% slowdown in
the general/dominant usage will only pass with some big fight.)
> I can see how this could be problematic for uninitialized values,
> return null or 0? Maybe this could be solved by adding a generic
> "zero"-value that is valid for all types?
This is not a problem. If the first value added is int and later we
transition int->Object, any unused position (slack due to the exponential
growing strategy) becomes nulls, but these values are not really contained
by the collection (they are in positions >= size()). If we ever transition
Object->int, slack elements are initialized with 0 but once again
they're not contained. If the collection (in Object state) does contains
nulls, then that collection simply cannot transition to the optimized
> I'm not saying that this is particularily elegent though...
More information about the lambda-dev