Skip to main content

CSE 331: Data abstraction: bounded integer sequence

This practice set uses the same ADT throughout. The questions build on one another, but you can work through them a few at a time. Try each question before opening its answer.

A BoundedIntSequence represents a mutable sequence of integers together with a fixed maximum capacity. The sequence may contain duplicates. Order matters. The constructor chooses the capacity. The sequence is full when its length equals its capacity.

In this implementation, the first size entries of the array represent the sequence, in order. The remaining entries are unused. Their values have no abstract meaning. The array's length represents the capacity. When size = 0, the sequence is empty.

All indices are zero-based. The notation a[0..n] denotes the first n elements, excluding index n. You may use Arrays.copyOf(a, n): for 0 <= n and n <= a.length, it returns a new array of length n containing the first n entries of a. Assume java.util.Arrays is imported.

Here is the class you'll work with. The methods are intentionally incomplete.

public class BoundedIntSequence {
    private int[] elements;
    private int size;

    // RI: ______________________________
    // AF: ______________________________

    /** Constructs an empty sequence with the given maximum capacity.
     *  @param capacity the maximum sequence length; requires
     *      0 <= capacity
     *  @effects constructs an empty sequence with the given capacity
     */
    public BoundedIntSequence(int capacity) {
        // TODO
    }

    /** @return the number of elements in this sequence */
    public int getSize() {
        return this.size;
    }

    /** @return a new, non-null array whose length is the sequence's
     *      length, containing exactly its elements in order
     */
    public int[] toArray() {
        // TODO
    }

    /** Appends x to the end of this sequence.
     *  @param x the integer to append
     *  @modifies this
     *  @effects if this sequence is not full, appends x without
     *      changing the capacity; otherwise leaves this unchanged
     *  @throws IllegalStateException if this sequence is full
     */
    public void append(int x) {
        // TODO
    }
}

Part 1: Understanding the representation

Question 1: Abstraction function

Write an abstraction function (AF) for BoundedIntSequence. The abstraction function should define both the sequence and its capacity.

Answer
// AF(this) = (the sequence elements[0..size],
//             the capacity elements.length).

The pair describes the abstract state. The unused entries' values are not part of that state, but the array's length is: it determines the capacity. For example, two objects can both contain [4], with capacities 1 and 2. Calling append(9) throws on the first object and succeeds on the second. Their abstract states must distinguish those capacities.

The AF is defined on states allowed by the RI, which Question 2 asks you to write. It need not assign an abstract state to fields that violate the RI.

The definition: Lecture 11's Abstraction functions.

Question 2: Representation invariant

Write a representation invariant (RI) for this implementation. Your RI should characterize which concrete states are valid.

Answer
// RI: elements != null and 0 <= size and size <= elements.length.

The backing array must be non-null. size must identify a valid prefix, including the empty prefix. There is no requirement that unused entries contain zeroes or that active entries be distinct.

By the AF, this RI ensures that the abstract sequence's length is between zero and its capacity. Keeping the capacity unchanged from one call to the next is a separate obligation on the methods. The RI alone does not compare states from different calls.

The definition: Lecture 11's Representation invariants.

Question 3: Valid concrete representations

Assume the RI from Question 2. Which of the following concrete states satisfy it? Select all that apply. Each array shown is non-null. Judge whether the RI is true of each state, regardless of whether the constructor and methods can produce that state.

  • A. elements = [4, 4, 0], size = 2
  • B. elements = [7, 0], size = 3
  • C. elements = [9], size = 0
  • D. elements = [], size = 0
  • E. elements = [1, 2, 3], size = -1
Answer

A, C, and D satisfy the RI.

  • A: Valid. Duplicates are allowed. The abstract state is the sequence [4, 4] with capacity 3.
  • B: Invalid because elements.length < size.
  • C: Valid. The abstract state is the empty sequence with capacity 1. The unused entry's value, 9, does not affect the RI.
  • D: Valid. The abstract state is the empty sequence with capacity 0.
  • E: Invalid because size < 0.

State C satisfies the RI even though the completed constructor and append in the answers below cannot produce it. The constructor initializes the array entries to zero. append only writes at size and increases size, so it cannot leave [9] with size = 0. Satisfying the RI does not require a state to be reachable by these methods.

The definition: Lecture 11's Representation invariants.

Part 2: Implementing the representation

Question 4: Write checkRep()

Recall that checkRep() is a private method that throws an exception if the RI is false and does nothing otherwise. Implement checkRep() for this class using the RI you wrote in Question 2. You may throw an IllegalStateException when the RI is violated.

private void checkRep() {
    // TODO
}
Answer
private void checkRep() {
    if (elements == null ||
        size < 0 ||
        elements.length < size) {
        throw new IllegalStateException("RI violated");
    }
}

The conditions describe violations of the RI. Any violation is enough to reject the state, so the conditions are connected with ||. The null check comes first. If elements is null, Java's short-circuit evaluation skips the remaining conditions, avoiding an attempt to read elements.length. The method changes no field.

The definition: Lecture 11's checkRep.

Question 5: Where should checkRep() be called?

An observer reads the abstract state without changing it. A mutator may change that state. Here, getSize() and toArray() are observers, and append() is a mutator.

For the public constructor and public methods shown here, which option gives the course's checkRep() placement rule? Choose one. For this question, the end of a method means its normal return.

  • A. At the beginning of the constructor and every public observer and mutator.
  • B. At the end of the constructor, at the beginning of every public observer, and at the beginning and end of every public mutator.
  • C. At the end of the constructor and every public mutator, but never in public observers because they do not modify the representation.
  • D. At the beginning and end of the constructor and every public method, including observers.
Answer

B gives the required placements.

  • The constructor checks at the end. The fields have been initialized, so the check can detect an invalid new object.
  • Public observers check at the beginning. An entry check can detect an RI that code outside the class broke between calls. Question 8 examines how a client could reach the array.
  • Public mutators check at the beginning and end. These checks detect an invalid starting state or an invalid state left by the mutation.

The RI must be true when no method of the class is running. It may be false between assignments inside a method. A private helper may be called at such a point, so this placement rule does not require the helper to check the RI.

The rule: the code-quality guide. Lecture 11 also explains the private-helper exception.

Question 6: Constructor

Implement the constructor according to its specification. Assume the caller satisfies 0 <= capacity. Include the required checkRep() call. Explain why the resulting object satisfies the RI and represents the empty sequence with the requested capacity.

public BoundedIntSequence(int capacity) {
    // TODO
}
Answer
public BoundedIntSequence(int capacity) {
    this.elements = new int[capacity];
    this.size = 0;
    checkRep();
}
  • Since 0 <= capacity, new int[capacity] creates a non-null array of length capacity.
  • Setting size = 0 satisfies 0 <= size and size <= elements.length, so the RI is true.
  • By the AF, the first zero entries form the empty sequence. The array's length gives the requested capacity.
  • The final checkRep() changes no field and does not throw, since the RI is true.

The rule: the code-quality guide.

Part 3: Observers and representation exposure

Question 7: Observer correctness

The original implementation of getSize() returns this.size.

  1. What concrete condition may getSize() assume at the start of a public call on a valid object, even though its specification has no precondition?
  2. Explain why returning this.size satisfies the abstract postcondition. Refer explicitly to the AF and RI. Account for the unchanged abstract state as well as the returned value.
  3. Rewrite getSize() to include the required checkRep() call.
Answer
  1. It may assume the RI: elements != null, 0 <= size, and size <= elements.length.
  2. The RI ensures that the first size entries form a valid prefix. By the AF, that prefix is the abstract sequence, so the sequence has exactly size elements. Returning this.size therefore returns the promised length. No field changes, so the sequence, capacity, and RI are unchanged. With no @modifies clause, the specification requires the abstract state to remain unchanged.
  3. The public observer checks the representation at its beginning:
public int getSize() {
    checkRep();
    return this.size;
}

The RI is true at entry, so checkRep() returns without changing any field. The method then returns size, so it terminates.

The rule: Lecture 11's ADT method correctness.

Question 8: Implement toArray()

Implement toArray() according to its specification, including the appropriate checkRep() call. Explain why returning this.elements directly would be incorrect. Would returning a defensive copy of the entire backing array satisfy the specification for every valid state? A defensive copy is a separate object that a client can change without changing the representation.

public int[] toArray() {
    // TODO
}
Answer
public int[] toArray() {
    checkRep();
    return Arrays.copyOf(this.elements, this.size);
}
  • The copy satisfies the specification. The RI ensures that elements is non-null and 0 <= size <= elements.length. Arrays.copyOf returns a new array containing exactly the active prefix. By the AF, those entries are the abstract sequence. The method changes no field, so the RI, sequence, and capacity remain unchanged. Copying a finite prefix terminates.
  • Returning elements directly breaks the specification. The result would not be a new array. When the sequence is not full, the result would also include unused entries. The client would hold an alias, another reference to the same array, and could change the representation through it.
  • Copying the entire array fails for non-full states. The copy would include unused entries, so its length would exceed the sequence's length. Such a copy is correct in a full state, but does not satisfy the specification for every valid state.

Suppose toArray() returned elements directly. After appending 7 to an empty object, a client could write 99 into entry 0 of the returned array. The abstract sequence would change from [7] to [99] without an ADT operation. Yet the array's length and size would be unchanged, so this RI would still be true. checkRep() would detect nothing. Entry checks can detect exposure that breaks the RI. They cannot replace defensive copying.

With the correct copy, changing the returned array changes no entry in the object's array. Since each entry is an int, there are no references to mutable elements that would need further copies.

The definitions: Lecture 11's Copy in, copy out and What correct means for an ADT method.

Part 4: Mutators and correctness

Question 9: Implement append(int x)

Implement append(int x) according to its specification. Include the appropriate checkRep() calls. Your implementation must leave the object unchanged when it throws because the sequence is full.

Explain why both a successful append and the exceptional case preserve the RI and satisfy the specification, including its promise about capacity.

public void append(int x) {
    // TODO
}
Answer
public void append(int x) {
    checkRep();
    if (this.size == this.elements.length) {
        throw new IllegalStateException("sequence is full");
    }
    this.elements[this.size] = x;
    this.size++;
    checkRep();
}
  • The entry check changes nothing. The RI is true at entry, so checkRep() returns without throwing or changing any field.
  • The full case leaves the object unchanged. By the AF, the sequence is full exactly when size == elements.length. The method throws the specified exception before changing the array or size. The RI is therefore still true at the exceptional exit. A second check on this branch would check the same state.
  • The non-full case preserves the RI. Write size_0 for the value of size at entry. The RI and the failed equality check give 0 <= size_0 and size_0 < elements.length, so the array write uses a valid index. After the increment, 0 <= size_0 + 1 <= elements.length. The array is still non-null, so every RI clause is true. The increment cannot overflow because its result is at most the array's length.
  • The non-full case appends the promised element. The entries before size_0 are unchanged. Entry size_0 now contains x, and the new size includes it in the active prefix. By the AF, the new sequence is the old sequence followed by x. The array's length is unchanged, so the capacity is unchanged too.
  • Both cases terminate. The full case throws immediately. The non-full case performs the write and increment, then calls checkRep() on the valid result and returns.

The rule: Lecture 11's ADT method correctness.

Question 10: RI versus specification

Consider this implementation of append, starting from a valid state that is not full. The checkRep() calls are omitted so you can judge the state changes themselves. The specification is repeated above the method:

/** Appends x to the end of this sequence.
 *  @param x the integer to append
 *  @modifies this
 *  @effects if this sequence is not full, appends x without
 *      changing the capacity; otherwise leaves this unchanged
 *  @throws IllegalStateException if this sequence is full
 */
public void append(int x) {
    if (this.size == this.elements.length) {
        throw new IllegalStateException();
    }
    this.elements[this.size] = x;
}

Which statement is correct? Choose one. To check your answer, trace append(7) on an initially empty object with capacity 2. State the fields and abstract state afterward, then give a repair if needed.

  • A. It violates the RI but satisfies the specification.
  • B. It preserves the RI but violates the specification.
  • C. It violates both the RI and the specification.
  • D. It satisfies both the RI and the specification.
Answer

B. It preserves the RI but violates the specification.

  • The trace leaves the sequence empty. Initially, elements is [0, 0] and size is 0. The call writes 7 at index 0, leaving elements = [7, 0] and size = 0. By the AF, the abstract state is still the empty sequence with capacity 2. The specification requires [7] with capacity 2.
  • The RI is preserved. In any valid state that is not full, 0 <= size < elements.length, so the write uses a valid index. size does not change, and the array remains non-null. All RI clauses remain true.
  • The specification is violated. The AF ignores the values at or after index size. Writing x at index size without incrementing size leaves the abstract sequence unchanged. The required sequence has one more element, so the postcondition is false even though the RI is true.
  • Incrementing size repairs the state change. Add this.size++; after the array write. Restore the entry and final checkRep() calls for the complete implementation in Question 9.

The rule: Lecture 11's ADT method correctness.