1

I am trying to make a CONTAINER class that maintains an array of CRITTER objects (that I have already created and tested. Note, there are various CRITTER subspecies, that are inheriting from the CRITTER super class). The aim is to add and remove CRITTER objects from this array. This is what the CONTAINER class looks like:

class
    CONTAINER
    create
    make

feature

    num: detachable INTEGER
    list: ARRAY[CRITTER]

    make
        local

        do
            create list.make_empty
            num := 0
        end

        addCritter(critter: CRITTER)
        do
            list.put(animal, num)
            num := num + 1
        end

        removeCritter(critter: CRITTER)
        do    
             list.put (list.at (num), ???) -- put last element in position of element to be removed
             list.remove_tail (num) -- remove tail
             num := num - 1
        end

end

Two issues: Firstly, I can instantiate the CONTAINER class inside APPLICATION, but when I call

create container.make
container.addCritter(myCritter)

I get a precondition, invalid index violation error on the second line. This may be because I have not set the upper and lower bounds of the array. However, when I try to do so, I get syntax errors. Which is the way to solve this issue?

Secondly, in order to remove an object from the array, it would help if I could get hold of the index value, but I can't see any function that does this, unless I am missing something.

cadebe
  • 651
  • 1
  • 12
  • 35

1 Answers1

1

ARRAYs are usually used for fixed-length containers. In your case, with lots of dynamic changes, it's better to use more dynamic structures, for example, ARRAYED_LIST. Similar to ARRAY it provides features to access items by their index, but there are also more convenient ones. New elements can be added by using feature extend. Old elements can be removed by using feature prune if only one element matching a given one needs to be removed, or prune_all, if all matching elements need to be removed. The word "matching" denotes either reference or object equality, depending on which comparison criteria is required: = or ~. The comparison criteria is changed using feature compare_objects.

Some general observations:

  • There is no need to track number of elements yourself, usually there is a feature count that provides this number.
  • Indexes in Eiffel usually start with 1, not 0.
  • The declaration detachable INTEGER is equivalent to INTEGER because INTEGER is expanded and all expanded types are attached regardless of any attachment marks.

The following discussion might also be useful: How to initialise an array of objects in Eiffel?

Community
  • 1
  • 1
Alexander Kogtenkov
  • 5,770
  • 1
  • 27
  • 35