Some Notes for AP AB Test
-
To use a HashSet with user defined Objects we must define the hashCode method.
Otherwise the 2 Objects defined below will have a different HashCode.
Person2 p = new Person2("Tom","Jones");
System.out.println(p.hashCode());
Person2 p2 = new Person2("Tom","Jones");
System.out.println(p2.hashCode());
-
If you are using HashSet with user defined Objects you must implement the equals function, otherwise contains will not work even if 2 Objects Hash to the same thing.
-
Person2 p = new Person2("Tom","Jones");
Person2 p2 = new Person2("Tom","Jones");
h.put(p,"336-5365");
h.put(p2,"452-0286");
String s1 = h.get(p);
String s2 = h.get(p2);
Without equals being defined s1 and s2 would be different.
HashMap has under it an array of pointers to a linked list.
In this case we will not be able to get the information back. If we define equals, Tom Jones is only in there once with 452-0276. We probably want to hash set on more than first and last name, like zip, phone - then we can have two different Tom Jones in list.
-
HashMap resolves collisions by chaining.
-
When the HashMap array gets > 3/4 full it doubles size and redistributes data.
- Array is used under a Stack (you would think it would be a linked list, but the overhead in doubling size of array and recopying (log n times) is cheaper than creating a new node each time.