14.3. Using Swarm Arrays

The Swarm Array is the easiest to use of the Swarm collections. At create-time, the size of the Array is set. For example, to create an Array called foods that has 15 elements, this code will get the job done:

id <Arraya> foods; 
food=[Array create: [self getZone] setCount: 15];

If it is necessary to add elements to the Array, then the setCount:method of the Array class can be used to increase the size ofthe Array.

Entries are inserted, accessed, and removed from the Array in a rather obvious way. As in C, the numbering of the Array elements begins with 0, so the last element in the Array has the index value 14. To insert an object called steak into the foods Array at index value 6, the appropriate command is:

[foods atOffset: 6 put: steak];

When it is necessary to retrieve the steak object, this will do:

retrievedObject=[foods atOffset: 6];

A Swarm Array object will allow quick access of any particular object because the objects are indexed by an integer.

An Array will work like a Swarm List for the purposes of repetitive processing. Since an Array includes a fixed number of objects, they can easily be accessed with for loops, but while loops will work just as well. An Array object can be told to create an index object for itself, and that index can be used in the way that we described in the chapter on Lists.

There is only one surprise awaiting users of the Array protocol: objects cannot be removed from Arrays. Since the Array protocol's major strength is its speed, and the speed depends on maintaining a fixed list of items, the remove method of the Collections protocol is disabled in Array. Rather than remove an item from an Array, one must put nil at a position in the Array. This achieves the same effect as remove, but it preserves the Array "placeholder" so that future objects can be inserted at that spot.