CSC152 2004F, Class 42: Vectors Admin: * Yay! Everyone is here on time! * No alumna talk today! * Math/CS lunch! * Evil thieves stole projectors and other stuff Overview: * About vectors * Testing! /Today's Goals/ * Learn more about this very useful class. * Think more about how we read documentation. * Think more about how we write tests. /Four Key Aspects of ADTs/ * Philosophy * Vectors are arrays that can expand when you need more room * Vectors provide lots of related methods that programmers normally use * remove(int index) * Remove the thing at position index, shift everything left * Shrinks! * add(int index, Object value) * Add something at position index, shift everything right * Expands! * What is the running time? Probably O(n) * Methods * Array-like * set(int index, Object value) * pre: Vector must be nonempty * pre: 0 <= index < size() * get(int index) * pre: 0 <= index < size() * size() * "construct" * setSize(int newSize) * Design question: How should they automatically expand? * Implementation * Have a field that contains an array * If you need more room, make a new array and copy the data over * Application /Learning Vector Methods Through Testing/ * Detour: How can you call a new method from a main? * Strategy one: Create an object in the appropriate class * Strategy two: Designate the method as something that does not need an object to associate itself with (only needs parameters) * We call such methods "class methods" or "static methods" * Such methods cannot access most fields of the class * Static methods are traditionally accessed as ClassName.methodName(params) * The initial size of vectors is: 0 * If you try to set the initial element of a vector without changing the size: It crashes (throws an exception) * set and get behave the way we expect Some programmers (or philosophers of programming) advocate writing the tests for your ADTs before you implement your ADTs! * Test-driven development Coming Wednesday: SORTING! You do not need to study any of this in advance * Merge sort * Bubble sort * Insertion sort * Heap sort! * Selection sort * Quicksort * Bucket sort * Radix sort /Notes for the World Folks/ public class ExceptionTester { public static void main(String[] args) throws Exception { try { throw new NotAVerb(); } catch (Exception e) { pen.println("OOh ... " + e.toString(); } } } // You walk into MathLAN. You see: leigh, brad, computer1, computer2, ... chair1, chair2, angeline, invisibleprojector, ... Action: Pick up computer Sorry, nothing here is called computer. Try computer1 or computer 2. Action: Pick up computer1 Sorry, it is too heavy. Action: Yell at computer1 It explodes. You are now dead. Please play again.