forked from lahiruroot/Java-challenge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHashTable.java
82 lines (70 loc) · 1.89 KB
/
HashTable.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
package Hashtable;
import java.util.ArrayList;
public class HashTable {
private int size = 7;
private Node[] dataMap;
class Node{
String key;
int value;
Node next;
Node(String key, int value){
this.key=key;
this.value=value;
}
}
public HashTable(){
dataMap = new Node[size];
}
public int hash(String key){
int hash=0;
char[] keyChars =key.toCharArray();
for (int i = 0; i < keyChars.length; i++) {
int asciiValue = keyChars[i];
hash = (hash+asciiValue*23) % dataMap.length;
}
return hash;
}
public void set(String key, int value){
int index= hash(key);
Node newNode = new Node(key, value);
if (dataMap[index]==null){
dataMap[index]=newNode;
}else {
Node temp = dataMap[index];
while (temp.next!=null){
temp=temp.next;
}
temp.next=newNode;
}
}
public int get(String key){
int index = hash(key);
Node temp = dataMap[index];
while (temp !=null){
if (temp.key==key)return temp.value;
temp=temp.next;
}
return 0;
}
public ArrayList keys(){
ArrayList<String> allKeys = new ArrayList<>();
for (int i = 0; i < dataMap.length; i++) {
Node temp = dataMap[i];
while (temp!=null){
allKeys.add(temp.key);
temp=temp.next;
}
}
return allKeys;
}
public void printTable(){
for (int i = 0; i < dataMap.length; i++) {
System.out.println(i+":");
Node temp = dataMap[i];
while (temp!=null){
System.out.println(" {"+temp.key+"= "+temp.value+"}");
temp=temp.next;
}
}
}
}