December 21, 2024

SortedCollection

 

SortedCollection is a subclass of OrderedCollection and differs in that the elements of an instance of the class are placed at positions determined by a sorting criteria.
SortedCollection has one instance variable sortBlock that acts as the function for sorting. The only addition message that is used is add:

To see how this works consider the following

sortedDeadArtists := SortedCollection new.
sortedDeadArtists add: 'Peter Hobbs';
                  add: 'Duncan Grant';
                  add: 'Prunella Clough';
                  add: 'Mario Dubsky';
                  add: 'Harry Thubron';
                  add: 'Victor Vaserely';
                  add: 'Roger Hilton';
                  add: 'Henry Moore';
                  add: 'Barbara Hepworth';
                  add: 'Jacob Epstein'

This answers with the argument to the last add: message 'Jacob Epstein', but if we inspect the receiver sortedDeadArtists we find it represented as
SortedCollection ('Barbara Hepworth' 'Duncan Grant' 'Harry Thubron' 'Henry Moore' 'Jacob Epstein' 'Mario Dubsky' 'Peter Hobbs' 'Prunella Clough' 'Roger Hilton' 'Victor Vaserely')

The sorting criteria has determined that the strings are placed in an alphabetical order. Why so? The default sorting criteria uses the message expression
predecessor <= successor

If, as in the case of 'Peter Hobbs' <= 'Duncan Grant', the answer is false the position of the elements in the collection is reversed.
Therefore the elements of a sorted collection must must be able to respond to the comparison messages.
<
<=
=
>=

To change the sorting criterion the message sortBlock: is used with a block argument containing the code that defines the new criterion.

To reverse the order of sortedDeadArtists we can use the following:

sortedDeadArtists sortBlock: [: predecessor :successor| predecessor >= successor]

This answers with the receiver sortedDeadArtists, which has a textual representation of
SortedCollection ('Victor Vaserely' 'Roger Hilton' 'Prunella Clough' 'Peter Hobbs' 'Mario Dubsky' 'Jacob Epstein' 'Henry Moore' 'Harry Thubron' 'Duncan Grant' 'Barbara Hepworth')

Most of the messages in the protocol of SortedCollection behave similarly to its superclass OrderedCollection. I intend to concentrate on the sort block by using another scenario to illustrate its use.

Next page » The retrospective collection

Previous page « The exhibition collection

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page