list literal gotcha and suggestion

Mark Thornton mthornton at
Thu Oct 1 13:04:12 PDT 2009

Mark Thornton wrote:
> Reinier Zwitserloot wrote:
>> For example, instead of stubbornly denying that Set literals aren't as  
>> important as List literals, can you, as an avid set user, shed some  
>> light on how acceptable some of the alternative proposals are, such as:
>> [1, 2, 3].toSet();
>> new Set[1, 2, 3];	//keep in mind that without the 'new', this syntax  
>> is pretty much impossible to integrate into the existing java grammar,  
>> due to looking like an array dereference operation.
>> new HashSet<>([1, 2, 3]);
> There is another alternative: The value [1,2,3] should be both a List 
> and a Set while [1, 2, 1] would be just a List. As the elements are 
> compile time constants the compiler can easily check for duplicates. If 
> any element appears more than once, then the result is just a List, 
> otherwise it implements both List and Set.

A complication with this alternative is the implementation of equals for 
set literals as they are also list literals:

boolean equals(object o) {
    if (o instanceof List)
       return listEquality((List)o);
    if (o instanceof Set)
       return setEquality((Set)o);
    return false;

Where listEquality compares elements in order as specified in 
List.equals, and setEquality acts as specified by Set.equals.

Mark Thornton

More information about the coin-dev mailing list