-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
49 lines (43 loc) · 983 Bytes
/
HashTable.java
File metadata and controls
49 lines (43 loc) · 983 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
public class HashTable {
private class Node {
private Object key;
private Object value;
private Node next;
}
private Node[] buckets;
public HashTable(int numberOfBuckets) {
this.buckets = new Node[numberOfBuckets];
}
public void put(Object key, Object value) {
int hash = hash(key);
for( Node n = buckets[hash]; n != null; n = n.next ) {
if( key.equals(n.key) ) {
n.value = value;
return;
}
}
Node n = new Node();
n.key = key;
n.value = value;
n.next = buckets[hash];
buckets[hash] = n;
}
public Object get(Object key) {
int hash = hash(key);
for( Node n = buckets[hash]; n != null; n = n.next ) {
if( key.equals(n.key) )
return n.value;
}
return null;
}
private int hash(Object key) {
return (key.hashCode() & 0x7fffffff) % buckets.length;
}
public static void main(String[] args) {
HashTable h = new HashTable(4);
for( int i=0; i<10; i++ ) {
h.put(i, "v" + i);
}
System.out.println(h.get(5));
}
}