Created
May 27, 2020 18:26
-
-
Save lakamsani/6e0674dcead771c804810733a50876ad to your computer and use it in GitHub Desktop.
hash collissions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HashMap<Key,Value> { | |
private int numPairs = 100000; | |
private Value[] vals = (Value[]) new Object[numPairs]; | |
private Key[] keys = (Value[]) new Object[numPairs]; | |
private int hash(Key key) { | |
return (key.hashCode() & 0x7fffffff) % M; | |
} | |
public Value put(Key key, Value val) { | |
int i; | |
for (i = hash(key); keys[i] != null; i = (i+1)%M) { | |
if (keys[i].equals(key)) | |
break; | |
keys[i] = key; | |
vals[i] = val; | |
} | |
} | |
public Value get(Key key) { | |
for (int i = hash(key); keys[i] != null; i = (i+1)%M) { | |
if (keys[i].equals(key)) | |
return vals[i]; | |
} | |
return null; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HashMap<Key,Value> { | |
private int numChains = 100; | |
private Node[] chainArray = new Node[numChains]; | |
private static class Node { | |
private Object key; | |
private Object val; | |
private Node next; | |
} | |
private int hash(Key key) { | |
return (key.hashCode() & 0x7fffffff) % M; | |
} | |
public Value put(Key key, Value val) { | |
int i = hash(key); | |
for (Node x = chainArray[i]; x != null; x = x.next) { | |
if (key.equals(x.key)) { | |
x.val = val; | |
return; | |
} | |
chainArray[i] = new Node(key, val, chainArray[i]); | |
} | |
} | |
public Value get(Key key) { | |
int i = hash(key); | |
for (Node x = chainArray[i]; x != null; x = x.next) { | |
if (key.equals(x.key)) | |
return (Value) x.val; | |
} | |
return null; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment