The ArraySet Class

Here is the class, with its fields and constructor:

public class ArraySet<T> implements Set<T> {

  private T[] arr;   // the backing array
  private int size;  // how many items the set holds

  @SuppressWarnings("unchecked")
  public ArraySet() {
    arr = (T[]) new Object[10];  // start with room for 10 items
    size = 0;                    // the set starts empty
  }

  // ... the operations will go here
}

The two fields are the representation we designed: the backing array and the size. The constructor allocates room for ten items and uses the same unchecked cast as ArrayList, for the same reason.

The size operation reads the field directly:

@Override
public int size() {
  return size;
}

Every remaining operation has to locate an item, so we write that search once, as a private helper:

private int indexOf(T item) {
  for (int i = 0; i < size; i++) {
    if (arr[i].equals(item)) {
      return i;
    }
  }
  return -1;
}

It is the same linear search and the same -1 convention as ArrayList.