-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhashtable.java
More file actions
113 lines (100 loc) · 2.95 KB
/
hashtable.java
File metadata and controls
113 lines (100 loc) · 2.95 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import java.util.LinkedList;
class main{
static public class Map{
private static final int SIZE = 100;
private HashEntry table[] = new HashEntry[SIZE];
public void put(String key , String val){
int hash = this.generateHash(key);
HashEntry newHashEntry = new HashEntry(hash,key,val);
if(this.table[hash]==null){
this.table[hash] = newHashEntry;
}else{
HashEntry temp = table[hash];
while(temp!=null){
if(temp.key == key){
temp.val=val;
return;
}
temp = temp.next;
}
temp = newHashEntry;
}
}
private int generateHash(String key){
int val = 0;
for(int i=0;i<key.length();i++){
val+=(int)key.charAt(i);
val%=this.SIZE;
}
return val;
}
public boolean containsKey(String key){
int hash = this.generateHash(key);
HashEntry temp = this.table[hash];
while(temp!=null){
if(temp.key==key){
return true;
}
}
return false;
}
public boolean containsValue(String val){
for(HashEntry entry : this.table){
while(entry!=null){
if(entry.val==val){
return true;
}
}
}
return false;
}
public String get(String key){
int hash = this.generateHash(key);
HashEntry temp = this.table[hash];
while(temp!=null){
if(temp.key==key){
return temp.val;
}
temp=temp.next;
}
return null;
}
@Override
public String toString(){
String res="";
for(HashEntry Entry : this.table){
if(Entry!=null){
while(Entry!=null){
res+="("+Entry.key+" : "+Entry.val+"),";
Entry = Entry.next;
}
res+="\n";
}
}
return res;
}
}
static public class HashEntry{
int hash;
String key;
String val;
HashEntry next;
HashEntry(int hash,String key , String val){
this.hash=hash;
this.key=key;
this.val=val;
this.next=null;
}
@Override
public String toString(){
String res = "";
res+=this.key+" "+this.val;
return res;
}
}
public static void main(String args[]){
Map map = new Map();
map.put("me","mauank");
System.out.println(map);
}
}