-
Notifications
You must be signed in to change notification settings - Fork 28
/
Copy pathBasicHashTable.java
100 lines (80 loc) · 1.79 KB
/
BasicHashTable.java
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
89
90
91
92
93
94
95
96
97
98
99
100
package ds_007_hashtables;
public class BasicHashTable {
private static final int DEFAULT_CAPACITY = 10;
private Integer[] data;
private int capacity;
private int size;
public BasicHashTable() {
this(DEFAULT_CAPACITY);
}
public BasicHashTable(int capacity) {
this.capacity = capacity;
init();
}
private void init() {
data = new Integer[capacity];
size = 0;
}
public boolean put(int element) {
if(data[hashFunction(element)] != null) {
System.out.printf("\t\tError: [%d] which mapped to [%d] is already occupied!\n", element, hashFunction(element));
return false;
}
data[hashFunction(element)] = new Integer(element);
size++;
return true;
}
public Integer get(int element) {
return data[hashFunction(element)];
}
public Integer remove(int element) {
Integer removed = data[hashFunction(element)];
if(removed != null) {
data[hashFunction(element)] = null;
size--;
}
return removed;
}
private int hashFunction(int element) {
int hashValue = element%capacity;
return hashValue;
}
// trival
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean isFull() {
return size == capacity;
}
public void print() {
System.out.print("Hash Table: ");
if(isEmpty()) {
System.out.print("Empty");
} else {
for(int i = 0; i < capacity; i++) {
if(data[i] != null) {
System.out.printf("%2d ", data[i]);
}
}
}
System.out.print("\n");
}
public void printVerbose() {
System.out.print("Hash Table: ");
if(isEmpty()) {
System.out.print("Empty");
} else {
for(int i = 0; i < capacity; i++) {
if(data[i] != null) {
System.out.printf("%2d ", data[i]);
} else {
System.out.print(" - ");
}
}
}
System.out.print("\n");
}
}