December 21, 2024

The Protocol of Array

 

By referencing an array with a variable, say baconArray, and evaluating the following expression, an array of sufficient size to store 5 objects is instantiated.

baconArray := Array new: 5

The array's size can be confirmed with

baconArray size

This returns 5

At this stage all the stored elements reference nil.

1 2 3 4 5
nil nil nil nil nil

 

The next expressions add elements to the array.
fbaconDictionary has already been created, setOfPubs and birthDate are instantiated as follows:

setOfPubs := Set new.
setOfPubs add: 'French House';
          add: 'Colony Room';
          add: 'Dog and Duck'.

birthDate := Date newDay: 28 month: #October year: 1909.

baconArray at: 1 put: 'Francis Bacon';
           at: 2 put: fbaconDictionary;
           at: 3 put: setOfPubs;
           at: 4 put: birthDate;
           at: 5 put: 666

1 2 3 4 5
'Francis Bacon' fbaconDictionary setOfPubs birthDate 666

 

However, if evaluated, the following code would throw an exception.

baconArray at: 6 put: 'George'

An array is fixed size; it cannot be extended. The argument to at: must lie within the range of indexes that have been created. Furthermore, one cannot shrink an array by using remove:, but one can replace an element with another object. For example:

baconArray at: 1 put: 'The Old Devil'

replaces the string at index 1 with 'The Old Devil'. The message answer is the argument supplied to put:

baconArray includes: 'Francis Bacon'

returns true

baconArray isEmpty

returns false. Similarly

newArray := Array new: 10.
newArray isEmpty

returns false. The isEmpty message sends a size message that implements a check on the number of indexable fields in the receiver. In this case the size message produces an answer of 10 and consequently the isEmpty message produces a false message answer. Only when the number of stored elements equals 0 is true returned.

baconArray at: 3

returns setOfPubs, the textual representation of which is

Set('Dog and Duck' 'Colony Room' 'French House')

The indexOf: selector can be used like this:

baconArray indexOf: setOfPubs

and returns 3

The message selector to:do: in the protocol of Number can be used to initialise an array, as illustrated in the next scenario.

Next page » A scenario illustrating the use of Array

Previous page « Array

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Up to top of page