The Array is Not Enough
E N D
Presentation Transcript
Lists Arrays
Key Insight The array is our friend (sort of) but… turn all values into numbers (smaller than the array’s size)
0 4 8 9 7 2 3 5 6 1 Let’s assume an array of 10 elements…
4 0 4 8 9 7 2 3 5 6 1 7 4 8
104 0 4 8 9 7 2 3 5 6 1 104 224 a modulo b = once you divide b into a, what’s left? 5 modulo 2 = ? 4 modulo 2 = ? 37 modulo 17 = ? 104 modulo 10 = ? 463325 modulo 9882 = ?
“Hello” 0 4 8 9 7 2 3 5 6 1
“Hello” 0 4 8 9 7 2 3 5 6 1 combine(72, 101, 108, 108, 111)
0 4 8 9 7 2 3 5 6 1 class Point { int x; int y; }
0 4 8 9 7 2 3 5 6 1 class Name { String first; String last; }
0 4 8 9 7 2 3 5 6 1 class Person { Name n; Address a; Education e; }
The processof converting arbitrary datainto a single numberis called hashing
Good News You don’t need to define these: Java provides hash codes String s = new String("Hello"); s.hashCode() • 69609650
class Point { int x; int y; } Point p1 = new Point(2, 3); Point p2 = new Point(3, 5); p1.hashCode() 1252169911 p2.hashCode() 2101973421 inti = 5; i.hashCode(); error: int cannot be dereferenced
Arrays Revisited 1 2 3 4 5 0
A New Collection Class 1 1 2 2 3 3 4 4 5 5 0 0 Hash Table
Array: Index determines where the value goes Hash Table: Hash determines where the value goes 1 1 2 2 3 3 4 4 5 5 0 0
A More General Idea: Mapping Person Company String Boolean Number Country A B Person Employer URL Visited? Country +Dialing Code Key Value
Point p1 = new Point(2, 3); Point p2 = new Point(3, 5); HashMap<Point, String> hmap = new HashMap<Point, String>(); hmap.put(p1, "Red"); hmap.get(p1) "Red" hmap.put(p1, "Blue"); hmap.get(p1) "Blue" hmap.get(p2) null p2 p1 1 2 3 4 5 0 Blue Red
A New Data Structure Primitive The key-value pair In Java, all keys must be the same type, all values the same type, but those two types can be different Basic operations: get and put