list literal gotcha and suggestion
Nick Parlante
nick.parlante at cs.stanford.edu
Sat Sep 26 13:37:34 PDT 2009
Hi there -- up until recently I taught Stanford's Tons Of Java course,
CS108, for many years, so I've got a good feel for how new engineers get
started with the language and where they have problems. I also run
http://javabat.com where you really see what beginner programmers write.
Looking at the Project Coin stuff, one corner of the syntax for
collection literals jumped out at me as a potential source of problems.
Here's the proposed syntax, as lifted from Mark Reinhold's slides.
List<Integer> piDigits = [ 3, 1, 4, 1, 5, 9, 2, 6, 5 ];
Set<Integer> primes = { 2, 7, 31, 127, 8191, 131071 };
My concern is that students will write code like this:
List<Integer> piDigits = new ArrayList<>({3, 1, 4, 1});
This code looks so reasonable but sadly does something unexpected, since
the set literal eliminates the second 1.
The students will write it this way, with the { }, since they are
accustomed to array initializers that way in Java, and also C/C++.
So here's my suggestion:
1. Use { } for list literals, not [ ]. It's most consistent with array
literals and avoids the above list/set gotcha.
2. Use [ ] for set literals, or if that causes problems, just don't have
a literal for sets. Lists and maps are the most common, so having a
syntax for those cases is the most important. Even without a special
syntax, a set is easy to express based on a list literal, like
new HashSet<Integer>({1, 2, 3, 1}) // { } meaning List here
It's nice that there's no gotcha with the slight []/{} mis-match going
this direction.
Cheers,
Nick
More information about the coin-dev
mailing list