-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryHashMap.java
More file actions
88 lines (70 loc) · 1.6 KB
/
Copy pathBinaryHashMap.java
File metadata and controls
88 lines (70 loc) · 1.6 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package com.java.ds.bst;
public class BinaryHashMap<K,V> {
int CAPACITY = 20;
Entry<K,V> elementData [] = new BinaryHashMap.Entry[CAPACITY];
int size;
public void put(K k, V v) {
int index = findIndex(k);
System.out.println("index for key "+ index);
Entry<K, V> entry = elementData[index];
if (entry == null) { //first entry at index
elementData[index] = new Entry(k,v);
size++;
} else {
addEntry(entry,k,v);
}
}
private void addEntry(Entry<K, V> root, K k, V v) {
Comparable<? super K> compr = (Comparable<? super K>) k;
int compareValue = compr.compareTo(root.key);
if(compareValue == 0){
root.value = v;
return;
}
if (compareValue > 0) {// right
if (root.getRight() == null) {
Entry<K, V> entry = new Entry(k,v);
root.setRight(entry);
size++;
} else {
addEntry(root.getRight(), k,v);
}
} else if (compareValue < 0) { // left
if (root.getLeft() == null) {
Entry<K, V> entry = new Entry(k,v);
root.setLeft(entry);
size++;
} else {
addEntry(root.getLeft(), k,v);
}
}
}
private int findIndex(K k){
return k.hashCode() % CAPACITY;
}
public int getSize(){
return size;
}
private static class Entry<K,V> {
private K key;
private V value;
private Entry<K,V> left;
private Entry<K,V> right;
public Entry(K k,V v) {
this.key = k;
this.value = v;
}
public void setLeft(Entry<K,V> left) {
this.left = left;
}
public void setRight(Entry<K,V> right) {
this.right = right;
}
public Entry<K,V> getLeft() {
return left;
}
public Entry<K,V> getRight() {
return right;
}
}
}