SWE/CS 332 In Class Exercise # 11
October 4, 2017


Consider the GrowList example:
//  GrowList is a mutable list that only gets longer.
public class GrowList <E> {

  private Map<Integer,E> values;

  public GrowList() { values = new HashMap<Integer,E>(); }
  // add to the end of the list
  public void add(E o) {
     values.put(size(), o);

  // number of values in list
  public int size() { return values.size(); }

  // get ith value in list
  public E get(int i) { 
     if (! inRange(i)) throw new IndexOutOfBoundsException("GrowList.get");
     return values.get(i);

  // update ith value in list;  return previous value or null if none
  public E set(int i, E o) {
     if (! inRange(i)) throw new IndexOutOfBoundsException("GrowList.set");
     return values.put(i, o);
  // private helper method
  private boolean inRange(int i) { return (i >= 0) && (i < size()); }

The abstraction function is that the indices in the GrowList are exactly the keys in the map, and the list element for each index is simply the associated value in the map. In other words the AF is:

[values.get(0), values.get(1), ... values.get(values.size()-1)]

One rep-invariant is that the map isn't null and the keyset of the map is exactly the integers 0..values.size()-1

Is that enough? What else might you want to add?

  1. Analyze each method with respect to the rep-invariant. Which method(s) require(s) the most attention?

  2. Repeat the exercise for the contracts. Which method(s) require(s) the most attention?

  3. Identify some rep states that don't satisfy the rep-invariant. How do the broken rep-invariants affect the behavior of the methods?

  4. Consider a method
        public void nasty() {
    that breaks the representation invariant. What are some simple implementations for nasty()?

  5. Does the presence of nasty() affect the correctness of the other methods in GrowList?
  6. Suppose we weakened the rep-invariant.
    • How could we do that? Would we want to change the rep?
    • Where would we need to change the code to make it correct?