teaching machines

CS 330 Lecture 31 – Generics and Templates

April 22, 2013 by . Filed under cs330, lectures, spring 2013.

Agenda

TODO

Code

UnwildList.java

package generics;

public class UnwildList {
  private Object[] items;
  private int size;
  
  public UnwildList() {
    size = 0;
    items = new Object[10];
  }
  
  public Object get(int i) {
    return items[i];
  }
  
  public int size() {
    return size;
  }
  
  public void add(Object newItem) {
    if (size == items.length) {
      Object[] newItems = new Object[size * 2];
      System.arraycopy(items, 0, newItems, 0, size);
      items = newItems;
    }
    
    items[size] = newItem;
    ++size;
  }
  
  public static void main(String[] args) {
    UnwildList l = new UnwildList();
    l.add("fornk");
    l.add("blapper");
    l.add("foobag");
    l.add("bjarne stroustrup");
    l.add(42);
    
    for (int i = 0; i < l.size(); ++i) {
      System.out.println(((String) l.get(i)).toUpperCase());
    }
  }
}

WildList.java

package generics;

public class WildList<T extends Feiock> {
  private T[] items;
  private int size;
  
  public WildList() {
    size = 0;
    items = (T[]) new Object[10];
  }
  
  public T get(int i) {
    return items[i];
  }
  
  public int size() {
    return size;
  }
  
  public void add(T newItem) {
    if (size == items.length) {
      T[] newItems = (T[]) new Object[size * 2];
      System.arraycopy(items, 0, newItems, 0, size);
      items = newItems;
    }
    
    items[size] = newItem;
    ++size;
  }
  
  public static void main(String[] args) {
    WildList<String> l = new WildList<String>();
    l.add("fornk");
    l.add("blapper");
    l.add("foobag");
    l.add("bjarne stroustrup");
//    l.add(42);
    
    for (int i = 0; i < l.size(); ++i) {
      System.out.println(l.get(i).toUpperCase());
    }
  }
}

WildList.cpp

#include <cassert>
#include <cstring>
#include <iostream>

template<typename T> class WildList {
  public:
    WildList();
    int size() const;
    T &operator[](int i);
    void operator+=(T newItem);

  private:
    T *items;
    int nitems;
    int capacity; 
};

template<typename T>
WildList<T>::WildList() :
  nitems(0),
  capacity(10) {
  items = new T[capacity]; 
}

template<typename T>
int WildList<T>::size() const {
  return nitems;
}

template<typename T>
T &WildList<T>::operator[](int i) {
  assert(i < nitems);
  return items[i];  
}

template<typename T>
void WildList<T>::operator+=(T newItem) {
  if (nitems == capacity) {
    T *new_items = new T[capacity * 2];
    memcpy(new_items, items, sizeof(T) * nitems);
    delete[] items;
    items = new_items;
    capacity *= 2;
  }

  items[nitems] = newItem;
  ++nitems;
}

int main(int argc, char **argv) {
  WildList<int> l;
  l += 5;
  l += 6;
  l += 7;
  for (int i = 0; i < 3; ++i) {
    std::cout << "l[i]: " << l[i] << std::endl;
  }
  return 0;
}

Haiku

Compilers cheer too
“Don’t know U, but I like U!”
“Code fits to a T!”