ADT Table



ADT Table



Keyed Items

public abstract class KeyedItem {
 private Comparable searchKey;
 public KeyedItem (Comparable key) {
   searchKey = key;
 }
 public Comparable getKey () {
   return searchKey;
 } }
public class City extends KeyedItem {
// the city is the searchKey
 private String country; private int pop;
 public City (String name, String land,
              int count) {
   super (name);
   country = land; pop = count;
 }
 public String toString () {
   return getKey() + ", " + country
          + ", " + pop;



Table Interface

public interface TableInterface {
 // invariant: no two items in the
 // in the table have the same key
  public boolean isEmpty ();
  public int length ();
  public KeyedItem
    retrieve (Comparable key);
 // insert throws exception if the key
 // is already present
  public void insert (KeyedItem item)
    throws TableException;
 // returns true for succesful deletion
  public boolean delete (Comparable key);
}



Table Implementations



Sorted Array Implementation

public class TableArrayBased
   implements TableInterface {
  final int MAX = 100;
  protected KeyedItem [] items;
  private int size;
  protected int position (Comparable k) {
//return 0..size (size only if not found)
  }
  public KeyedItem
     retrieve (Comparable k) {
    int p = position (k);
    int pk = items [p].getKey ();
    if ((p < size) &&
        (k.compareTo (items[p].getKey ())
         == 0)) {
      return items [p];
    } else {
      return null;
    } } }



Sorted Array Insertion

public void insert (KeyedItem item) {
  int p = position (item);
  if (p < size) {
    Comparable k = item.getKey ();
    Comparable pk = items[p].getKey ();
    if (k.compareTo (pk) == 0)
      throw new TableException ("dup");
  }
  if (size == MAX)
    throw new TableException ("full");
  for (int i = size - 1; i >= p; i++)
      items [i + 1] = items [i];
    items [p] = item;
    size++;
  }
}



Binary Search Tree Implementation

public class TableBSTBased
   implements TableInterface {
  protected BinarySearchTree [] tree;
  protected int size;
  public KeyedItem
     retrieve (Comparable k) {
    return tree.retrieve (k);
  }
  public void insert (KeyedItem item) {
    if (tree.retrieve (item.getKey ())
        != null)
      throw new TableException ("dup");
    tree.insert (item);  size++;
  }
  public void delete (Comparable k) {
    try { tree.delete (item.getKey ());
    } catch (TreeException e)
    { return false; }
    size--; return true; } }