How ArrayList and HashMap Work As you arrive 1. Get the handout 2. Snarf the code for today’s class 3. Go online to Piazza and take the “What should Mike review Wednesday?” poll After today you will… • Be able to explain how HashMap and ArrayList work • Be able to derive/reason about the runtimes of ArrayList and HashMap Derive, don’t memorize • “There is no doubt that Marley was dead. This must be distinctly understood, or nothing wonderful can come of the story I am going to relate. If we were not perfectly convinced that Hamlet's Father died before the play began, there would be nothing more remarkable in his taking a stroll at night…” Accessing the nth element of an array is O(1) String var = myArray[1]; //THE SAME SPEED?!? var = myArray[100000]; //Also the same speed myArray[100000] = “Ninjas”; Accessing elements of an array is very fast, but some other parts of arrays are more problematic. 1. You have to decide on their size up front 2. You can only index them by consecutive integers What if we want to expand an Array but we have no slots left? • Look at ArrayGrow.java • Answer questions 1 and 2 in the handout, then go on to 3 if you have time What if we want to add a new element at the beginning of the list? Now it makes sense: ArrayList • Add/Remove at (n-k)th element – O(k) because you need to move all the elements one to the right or left • Remove at end O(1) – so long as we don’t want to copy to a smaller array • Add at end O(1) – sort of. 99% of the time, it is really O(1) because we have empty slot. We normally ignore the other 1%. • Get/set kth element O(1) – because it’s an array! On to hashMap • Silly analogy • Apartment that assigns rooms based on phone number Ok, on to ArrayListHash • Like hashmap • Answer questions 4, 4 (numbering mishap), and 5 Now it makes sense: HashMap • Get an element based on key O(1): Just a lookup in an array • Check if a key exists: Just a lookup in the array • Set an element based on key O(1)*: another lookup, and we won’t worry about the situation in which we need to grow the hashmap Note that this only works if the hashCode function is good After today you will… • Be able to explain how HashMap and ArrayList work • Be able to derive/reason about the runtimes of ArrayList and HashMap Derive, don’t memorize