teaching machines

CS 245 Lecture 11 – Set and Generics

October 8, 2013 by . Filed under cs245, fall 2013, lectures.

Agenda

What Does This Do?

Code

VerdeganTest.java

package lecture11;

public class VerdeganTest {
  public static boolean isEven(int i) {
    return isOdd(i - 1);
  }

  public static boolean isOdd(int i) {
    if (i == 1) {
      return true;
    } else if (i == 0) {
      return false;
    }
    return /* i == 1 || */isEven(i - 1);
  }

  public static void main(String[] args) {
    System.out.println(isEven(2000000));
  }
}

Set.java

package lecture11;

public class Set<T> {
  private T[] items;
  private int nitems;

  public Set() {
    items = (T[]) new Object[100];
    nitems = 0;
  }
  
  public T get(int i) {
    return items[i];
  }

  public int size() {
    return nitems;
  }

  public boolean contains(T needle) {
    for (int i = 0; i < size(); ++i) {
      if (items[i].equals(needle)) {
        return true;
      }
    }
    return false;
  }

  public void add(T s) {
    if (!contains(s)) {
      items[nitems] = s;
      ++nitems;
    }
  }

  public static void main(String[] args) {
    Set<String> set = new Set<String>();
    System.out.println(set.size());
    set.add("blarp");
    System.out.println(set.contains("blarp"));
    
    String s = set.get(0);
  }
}

Haiku

Already have it!
Don’t need two Utah quarters.
I can do laundry!