-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashTable.java
More file actions
98 lines (79 loc) · 2.36 KB
/
HashTable.java
File metadata and controls
98 lines (79 loc) · 2.36 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
89
90
91
92
93
94
95
96
97
98
public class HashTable {
private static int SIZE = 16;
private HashEntry[] table = new HashEntry[SIZE];
public void insert(Integer key, String value) {
int index = key.hashCode() % table.length;
HashEntry entry = new HashEntry(key, value);
if (table[index] == null) {
table[index] = entry;
}
else {
HashEntry temp = table[index];
while (temp.next != null) {
temp = temp.next;
}
temp.next = entry;
}
}
public String get(Integer key) {
int index = key.hashCode() % table.length;
if (table[index] != null) {
HashEntry temp = table[index];
while (temp.key != key && temp.next != null) {
temp = temp.next;
}
return temp.value;
}
return null;
}
public class HashEntry {
int key;
String value;
HashEntry next;
HashEntry(int key, String value) {
this.key = key;
this.value = value;
this.next = null;
}
@Override
public String toString(){
return "[" + key + ", " + value + "]";
}
}
@Override
public String toString(){
int bucket = 0;
StringBuilder outputString = new StringBuilder();
for (HashEntry entry: table){
if (entry == null){
continue;
}
outputString.append("\n bucket[")
.append(bucket)
.append("] = ")
.append(entry.toString());
bucket++;
HashEntry temp = entry;
while (temp.next != null){
temp = temp.next;
outputString.append("->")
.append(temp.toString());
}
}
return outputString.toString();
}
public static void main(String[] args) {
HashTable hashTable = new HashTable();
// Put some key values.
for(int i=0; i<30; i++) {
hashTable.insert(i, String.valueOf(i));
}
// Print the HashTable structure
log("**** HashTable ***");
log(hashTable.toString());
log("\nValue for key(20) : " + hashTable.get(20));
}
private static void log(String msg) {
System.out.println(msg);
}
}