Today Book-keeping Exceptions Subscribe to sipb-iap-java-students Collections http://sipb.mit.edu/iap/java/ Play with problem set 1 No class Monday (MLK); happy Hunting Problem set 2 on Tuesday 1 2 So far... Handling errors OOP, inheritance What if there s an error? Abstract classes Interfaces Example: list of Objects, want to find one and return its index What if not in list? Traditional C response: values (like -1) return special Need the programmer to remember to notice and special-case it 3 4
Exceptions What is an Exception? Java response: throw an exception Exception is a standard Java class Abnormal return from function throw keyword exits out of current code Calling code needs to catch it Nearest enclosing and matching catch block (possibly in a calling function) gets the exception, or else the program ends 5 6 Throwing exceptions import java.util.nosuchelementexception; // Inside some class private int finditem(int n, int[] arr) throws NoSuchElementException { for (int i = 0; i < arr.length; i++) { if (arr[i] == n) return i; throw new NoSuchElementException(); Catching exceptions try { int offset = obj.finditem(17); // use offset somehow catch (NoSuchElementException e) { // handle appropriately 7 8
Exceptions syntax Catching throw obj: throws an Exception object Can have multiple catch blocks try {... catch (ExceptionType name) {... First catch block with matching exception class (or a superclass) is invoked Executes the try block until an exception occurs, then jumps to matching catch code finally block, if present, does clean-up after try code 9 10 Catching, cont d Runtime exceptions try { // some code if (something) throw new NoSuchElementException(); catch (ClassCastException e) { // We don t end up here catch (Exception e) { // We get caught here finally { // Do cleanup Checked (normal) exceptions must either be caught or declared with throws Unchecked exceptions must be derived from RuntimeException; don t have to be declared Implicitly passed to caller if not caught 11 12
Exception class boilerplate Digression public class MyException extends Exception { public MyException() { super(); public MyException(String s) { super(s); Data types influence your algorithms..and vice versa! 13 14 Container classes Generalities Often want to store variable amounts of data Can t use int[] arrays; constant size Don t want to keep writing linked lists Classes in java.util All subclasses of Collection interface All store Objects; need to cast to correct type when retrieving Java APIs to the rescue Various performance trade-offs No special requirements (mostly; working hashcode sometimes) http://java.sun.com/j2se/1.4.2/docs/guide/col Optimized for various situations 15 16
Generic collections Iterator Collection c; c.add(o); c.clear(); // Comes from somewhere // any Object // empties c Allows each element to collection to be accessed in turn if (c.isempty()) //... Common way to loop over contents using a while loop int numelems = c.size(); Collection c2; c = new ArrayList(c2); // Does a shallow copy Can t modify collection while iterating except via iterator 17 18 Iterators, an example Collections to arrays Iterator iter = c.iterator(); Object o = iter.next(); // Can t say: // Rect r = iter.next(); Collection.toArray() returns a generic Object[] Need to make sure the array is of the right run-time type Solution: create the correct type of array beforehand, use casting 19 20
Collections to arrays, an example Fast vs. Slow Collection c; // set and filled from somewhere MyObject[] array = new MyObject[1]; array = (MyObject[])c.toArray(array); Algorithmic complexity O(n): operation takes time proportional to size of set; searching for item in unsorted list O(1): operation takes constant time; searching for item in hash table 21 22 Lists List is an interface; multiple implementations Ordered Can contain duplicates Default add is to end of list Lists, an example List l; // comes from somewhere; couple of options l.add(new Integer(4)); // can t add an int l.add(new Integer(8)); l.add(new Integer(6)); Iterator iter = l.iterator(); Integer i = (Integer)iter.next(); System.out.println(i); // Prints 4 8 6 23 24
List options LinkedList: fast insertion, iteration ArrayList: fast indexed access Vector: deprecated, mostly List operations List l = new ArrayList(); Object o; // from somewhere // Insert at arbitrary point: l.add(o,2); // Return arbitrary element: // (slow in LinkedList) o = l.get(1); // Find index of an object (slow, uses.equals) int i = l.indexof(o); // Replace an element: l.set(0, o); 25 26 Sets Set options Mathematical set HashSet: generally fast No guarantees on ordering No duplicates (according to.equals()) TreeSet: somewhat slower, but stores in sorted order. Objects inserted must implement Comparable interface Can t store mutable objects (.hashcode() can t change) contains() is fast No special operations 27 28
Comparable objects Comparable is an interface implementors provide compareto method Returns positive if this > o Returns negative if this < o Returns 0 if this.equals(o) Using sets: HashSet Set s = new HashSet(); s.add(new Integer(3)); s.add(new Integer(2)); s.add(new Integer(3)); // has no effect System.out.println(s.size()); // is 2 Iterator iter = s.iterator(); Integer i = (Integer)iter.next(); System.out.println(i); // May print 2, 3 or 3, 2 29 30 Using sets: TreeSet Maps Set s = new TreeSet(); s.add(new Integer(3)); s.add(new Integer(2)); s.add(new Integer(3)); // has no effect System.out.println(s.size()); // is 2 Iterator iter = s.iterator(); Integer i = (Integer)iter.next(); System.out.println(i); // Always prints 2, 3 Associates value with a key Keys act like a Set HashMap and TreeMap classes 31 32
Using maps In summary Maps ages = new HashMap(); ages.put("alex", new Integer(17)); ages.put("mark", new Integer(22)); // Keys don t have to be Strings Iterators Collections: lists, sets, hashes if (ages.containskey("alex")) { //... Iterator iter = ages.keyset().iterator(); String name = (String)iter.next(); Integer age = (Integer)ages.get(name); System.out.println(name + ": " + age); // Could print in any order 33 34 Tuesday File I/O Tools for debugging Inner classes 35