teaching machines

CS 245 Lecture 8 – Arrays

February 13, 2014 by . Filed under cs245, lectures, spring 2014.

Agenda

TODO

Think About This

  1. What do arrays have going for them?
  2. What about arrays is not so great?
  3. You’re looking for something in an array. How many elements do you check until you find it?
  4. How does ArrayList work?


Program This

  1. constructor
  2. void add(String o)
  3. int size()
  4. void remove(int i)
  5. void remove(String s)
  6. int indexOf(String s)
  7. String get(int i)

Code

Table.java

package lecture08;

import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Insets;
import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.border.Border;
import javax.swing.table.DefaultTableModel;

public class Table extends JFrame {
  public Table() {
    JTable grid = new JTable(8, 4);
    DefaultTableModel model = (DefaultTableModel) grid.getModel();
    model.setValueAt("a", 0, 1);
    
    grid.setGridColor(Color.MAGENTA);
    grid.setShowGrid(true);
    add(grid);
    
    pack();
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
  }
  
  public static void main(String[] args) {
    new Table();
  }
}

BigArray.java

package lecture08;

public class BigArray {
  public static void main(String[] args) {
    int i = 1;
    while (true) {
      try {
        int[] nums = new int[Integer.MAX_VALUE - i];
        System.out.println(i);
        System.out.println(Integer.MAX_VALUE - i);
        break;
      } catch (OutOfMemoryError e) {
        i += 1000;
      }
    }
    // nums[i]
  }
}

OurrayList.java

package lecture08;

public class OurrayList {
  private String[] items;
  private int itemCount;
  
  public OurrayList(int initialCapacity) {
    items = new String[initialCapacity];
    itemCount = 0;
  }
  
  public OurrayList() {
    this(10);
  }
  
  public int size() {
    return itemCount;
  }
  
  public String get(int i) {
    if (i < 0 || i >= itemCount) {
      throw new IndexOutOfBoundsException("Hey, foobag! " + i + " isn't welcome here.");
    }
    return items[i];
  }
  
  public void add(String s) {
    // Are we full?
    if (itemCount == items.length) {
      String[] moreItems = new String[2 * items.length];
      for (int i = 0; i < items.length; ++i) {
        moreItems[i] = items[i];
      }
      items = moreItems;
    }
    
    items[itemCount] = s;
    ++itemCount;
  }
  
  public void remove(int i) {
    for (int j = i; j < itemCount; ++j) {
      items[j] = items[j + 1];
    }
    items[itemCount] = null;
  }
}

Haiku

I saved just five seats
Friend 6 and I had to share
Next day we married