CS 245 Lecture 8 – Arrays
Agenda
- what ?s
- think about this
- OurrayList
- program this
- a spellchecker
TODO
- Read pages 61-79 in Data Structures. 1/4 sheet.
Think About This
- What do arrays have going for them?
- What about arrays is not so great?
- You’re looking for something in an array. How many elements do you check until you find it?
- How does ArrayList work?
Program This
- constructor
- void add(String o)
- int size()
- void remove(int i)
- void remove(String s)
- int indexOf(String s)
- 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
Friend 6 and I had to share
Next day we married