Re: what is the initial value of arrays of object
On Sep 28, 10:38 am, Lew <no...@lewscanon.com> wrote:
bbo...@gmail.com wrote:
On Sep 28, 1:36 am, zerg <z...@zerg.org> wrote:
[lots of ideas deleted]
ArrayList literals. Maybe use [{item, item, item}] as the syntax (it
isn't currently legal with some different meaning, so no clash there).
Right now, we have the cumbersome
List<Foo> list = new ArrayList<Foo>();
Collections.addAll(list, item, item, item);
but, not to put too fine a point on it, that freaking blows.
List<Foo> list = [{item, item, item}];
is much nicer.
In between is the currently legal, and barely more complex,
List <Foo> list =
Arrays.asList( { aFoo, anotherFoo, moreFoo, enoughFooAlready } );
That's only thirteen characters longer than your suggestion, or a mere si=
x
with static import:
List <Foo> list = asList( { aFoo, anotherFoo, moreFoo, enoughFooAlready=
} );
or a mere four with:
List <Foo> list = asList( aFoo, anotherFoo, moreFoo, enoughFooAlready )=
;
and given the simplicity and very explicit self-documenting nature of
'asList', I doubt very much that the language will undergo a change just =
to
save four characters.
Methinks we're at least missing an array-taking/varargs constructor
for the common collection classes. And putting a collection factory
method in neither a collection class nor Collections amounts to hiding
it. :P
Map is the really annoying case, though. If you want a map initialized
with particular mappings, you tend to wind up with an initializer
block or some other such complexity.
A constructor that expects an array of two-element arrays of Object
(and throws IllegalArgumentException/ClassCastException as
appropriate), added to the common map implementations, would go a long
way:
Map<K,V> map = new HashMap<K,V>({{k1,v1}, {k2,v2}, {k3,v3}});
Or even add a HashMap literal, say
Map<K,V> = {[k1, v1], [k2, v2], [k3, v3]};
whose type is HashMap<K,V> with K the most specific common supertype
of the key expressions in the literal and V the most specific common
supertype of the values.
While they're at it, they might add a Pair<K,V> type, with [x, y]
being a pair literal, and put some Pair using methods in the APIs.
Map<K,V>s might get put(Pair<K,V>) equivalent to put(pair.getKey,
pair.getValue), and Map.Entry might implement Pair if Pair is an
interface.