Skip to content

Instantly share code, notes, and snippets.

@lakamsani
Created May 27, 2020 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lakamsani/6e0674dcead771c804810733a50876ad to your computer and use it in GitHub Desktop.
Save lakamsani/6e0674dcead771c804810733a50876ad to your computer and use it in GitHub Desktop.
hash collissions
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;
}
}
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