Proposal: Collection Literals
jjb at google.com
Tue Mar 31 09:55:50 PDT 2009
Actually my proposal was intended to address creation of mutable
collections. I should have mentioned this explicitly in the proposal, and
will do so. Here's the idiom I recommend. Suppose you want a LinkedHashSet
initialized to contain Santa's eight reindeer. This will do the trick:
Set<String> team = new LinkedHashSet<>(
["Dasher", "Dancer", "Prancer", "Vixen","Comet", "Cupid", "Donner",
I think it looks pretty good! The same idea works for all other standard
collection implementations, including maps.
On Tue, Mar 31, 2009 at 8:57 AM, Kris Nuttycombe
<kris.nuttycombe at gmail.com>wrote:
> On Tue, Mar 31, 2009 at 9:38 AM, Reinier Zwitserloot
> <reinier at zwitserloot.com> wrote:
> > Many reasons for not just having varargs constructors on collections
> > API classes:
> > 1. constructors don't infer generics.
> > 2. constructors don't make immutables. Even Arrays.asList doesn't.
> > This is how you make an immutable list of constants today:
> > Collections.unmodifiableList(Arrays.asList("foo", "bar"));
> > that, is, in a word, ridiculous. Even with constructor help, it woud
> > become:
> > Collections.unmodifiableList(new ArrayList<String>("foo", "bar"));
> > not much help, and arguably even worse.
> I was imagining something more along the lines of:
> Collections.<String>immutableList("foo", "bar"). Of course, this is
> currently possible to do as a third-party library, so if one is
> content with such syntax there's already a solution.
> > It would become, with Joshes proposal:
> > ["foo", "bar"]
> > which makes me smile.
> Yes, however his proposal does not address the issue of simplifying
> the construction of mutable collections with initial contents. Of
> course, as the original proposal mentions one can always use anonymous
> inner classes (Crazybob's contraption) for this.
> > 3. import statements. Okay, that's a small one, but nevertheless.
> > 4. Implementation is often irrelevant, when the list is immutable
> > anyway. Why force people to type ArrayList. For that matter, why force
> > people to -read- ArrayList? It's just 'A list with no surprises, which
> > is immutable'. That's easy enough to remember.
> > 5. varargs are fundamentally broken, though fortunately the proposal
> > to address this issue is on the project coin shortlist.
> > --Reinier Zwitserloot
More information about the coin-dev