list literal gotcha and suggestion

Joseph D. Darcy Joe.Darcy at Sun.COM
Thu Oct 1 14:32:15 PDT 2009


Mark Thornton wrote:
> 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.
>
>   

A class cannot simultaneously satisfy the List and Set contracts for 
equals; various properties fail to hold such as (a.equals(b) && 
a.equals(c) ==> b.equals(c)):
if listset.equals(list) && listset.equals(set), list.equals(set) will 
*not* be true.

-Joe




More information about the coin-dev mailing list