[concurrency-interest] need to use collection.sort w. CopyOnWriteArrayList but cant.....

Osvaldo Pinali Doederlein osvaldo@visionnaire.com.br
Tue, 01 Jun 2004 14:48:19 -0300


Doug Lea wrote:
>>i need ot add sort capability and tried doing it through the
>>Collections.sort but this fails cause the sort method eventually calls the
>>set method on the list iterator and this is not supported in the
>>CopyOnWriteArrayList.
>>do i have alternatives?
> 
> You could use something like (omitting any generic types you might be
> using here):
> 
>   Object[] array = list.toArray();
>   Arrays.sort(array);
>   list.clear();
>   list.addAll(Arrays.asList(array));
> 
> This is not too fast, but at least makes only two full copies
> per sort rather than a copy per element change.

I suppose we could have methods like sort() added to the List interface.
This would allow CopyOnWriteArrayList to override the method so this
workaround could be implemented transparently to the user, and also
more efficiently (using less reallocations/copies).  I never understood
why the Collections framework choose this anti-OO design of having most
algorithms as statics of utility classes like Arrays and Collections.
It makes sense only for the methods that operate on primitive types,
e.g. sort(int[]).  Add interfaces like Sortable() { void sort(); } just
in case some non-List collection can sort, and so on.  This suggestion
is too late for Tiger --trivial implementations are possible, but ideal
implementations of some methods, which could be optimized with direct
access to the collections' private members, may need more work and QA.
But Guy's problem may show that we should consider this in the future.

A+
Osvaldo

-- 
-----------------------------------------------------------------------
Osvaldo Pinali Doederlein                   Visionnaire Informática S/A
osvaldo@visionnaire.com.br                http://www.visionnaire.com.br
Arquiteto de Tecnologia                          +55 (41) 373-7400 #228