list literal gotcha and suggestion

Stephen Colebourne scolebourne at joda.org
Tue Sep 29 02:53:19 PDT 2009


Over the 1.4million LOC codebase I work on, I found 12 set literals.
We're not talking about large numbers. Interestingly, the majority of
these were constants, and may be more common than list constants.
There weren't any cases of parameter passing of a set literal.

That said, I strongly dislike the confusion apparent here. We should
avoid new puzzlers if possible. I'd prefer

List<String> list = {"1", "2", "3"} - List literal
Map<Integer, String> list = {1 : "1", 2 : "2", 3 : "3"} - Map literal
No set literal
(I don't think this conflicts with the array literals...)

Perhaps there is also an argument for adding the static of methods to
construct mutable Set/List:

Set<String> set = HashSet.of("1", "2", "3");  // mutable set
List<String> list = ArrayList.of("1", "2", "3");  // mutable list
List<String> list2 = {"1", "2", "3"};  // immutable list


One final thought. It would be possible to add a "method" to the list literal:

Set<String> set = {1, 2, 3}.toSet();  // immutable set

This approach would handle additional interfaces too:

SortedSet<String> set = {1, 2, 3}.toSortedSet();  // immutable sorted set
MultiSet<String> mset = {1, 2, 3}.toMultiSet();  // immutable
multiset/bag (if added to JDK)

Stephen


2009/9/29 Reinier Zwitserloot <reinier at zwitserloot.com>:
> Scanning my codebase, they are quite rare. As the set literals are
> causing rather a lot of pain, let's see some proof before going too
> far down this road.
>
> Pain caused by set literals:
>
>  - ambiguity of {} - is that the empty set or the empty map?
>  - set/list confusion.
>  - the parser becomes quite a bit more complicated to handle the
> difference between sets and maps.
>
>  --Reinier Zwitserloot
>
>
>
> On 2009/29/09, at 10:02, Mark Thornton wrote:
>
>> Reinier Zwitserloot wrote:
>>> new HashSet<>(["a", "b", "c"]);
>>>
>>> is too much effort in the rare cases where you need to initialize a
>>> set-typed parameter? This is java, not perl. Golfing isn't the end
>>> goal.
>>>
>> Without scanning my codebase I wouldn't expect Set parameters and
>> fields to be rare. I use Set's quite frequently.
>>
>> Mark Thornton
>>
>
>
>



More information about the coin-dev mailing list