/*********************************************** * CS2510 Fall 2011 * Lecture #24 * Maps, Hashing, Equality ***********************************************/ import java.util.*; import tester.*; class Hasher { // A list of lists of T with direct access ArrayList>> alist; int capacity; Hasher(int capacity) { this.capacity=capacity; alist = new ArrayList>>(capacity); for(int i = 0; i < capacity; i = i+1) { alist.add(new ArrayList>()); } } // hash - Returns the index of the given int in our list int hash(int i) { return i % capacity; } // contains - Is the given Pair in our Hasher boolean contains(int key) { for (Pair p : alist.get(hash(key))) { if (p.key == key) { return true; } } return false; } // Put the mapping into our list void put(int key, T val) { alist.get(hash(key)).add(new Pair(key, val)); } // get - Gets the value in our Hash for the given key T get(int key) { for (Pair p : alist.get(hash(key))) { if (p.key == key) { return p.val; } } throw new RuntimeException("No key found, so sorry."); } } class Pair { // Key defined for simplicity int key; V val; Pair(int key, V val) { this.key = key; this.val = val; } } class Alien { String name; boolean isgreen; int numheads; Alien(String name, boolean isgreen, int numheads) { this.name = name; this.isgreen = isgreen; this.numheads = numheads; } // An integer key to represent this Alien int hashKey() { if (isgreen) { return name.length() + numheads * 100; } else { return name.length() + numheads * 100 + 55; } } // hashCode - An integer key to represent this Alien public int hashCode() { if (isgreen) { return name.length() + numheads * 100; } else { return name.length() + numheads * 100 + 55; } } // equalTo - Is the given object an Alien and equal to this Alien public boolean equals(Object o) { if (o.getClass() == Alien.class) { Alien tmp = (Alien) o; return tmp.name == this.name && tmp.isgreen == this.isgreen && tmp.numheads == this.numheads; } else { return false; } } } class LectureExamples { Alien a1 = new Alien("Zaphod", false, 2); Alien a2 = new Alien("ET", false, 1); Alien a3 = new Alien("Paul", false, 1); Alien a4 = new Alien("Roger", true, 1); Alien a1bizarro = new Alien("Zaphod", false, 2); Hasher ahash = new Hasher(3); // Test our Hasher void testHasher(Tester t) { ahash.put(a1.hashKey(), a1); ahash.put(a2.hashKey(), a2); ahash.put(a3.hashKey(), a3); ahash.put(a4.hashKey(), a4); t.checkExpect(ahash.contains(a1.hashKey()),true); t.checkExpect(ahash.contains(a4.hashKey()),true); t.checkExpect(ahash.get(a2.hashKey()),a2); t.checkExpect(ahash.get(a3.hashKey()),a3); } // Tests our equals and hashCode methods for Alien void testEquality(Tester t) { // The following must hold true for any implementation of equals and hashCode: // If a1.equals(a1bizarro), then a1.hashCode() == a1bizarro.hashCode() t.checkExpect(a1.equals(a2),false); t.checkExpect(a1.equals(a1bizarro),true); t.checkExpect(a1.hashCode(),a1bizarro.hashCode()); } }