-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashMap.java
More file actions
97 lines (76 loc) · 2.01 KB
/
HashMap.java
File metadata and controls
97 lines (76 loc) · 2.01 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
public class HashMap{
/*
Always a prime number as a size for the hash_table
to reduce the collision.
*/
private final static int HASH_SIZE = 7;
private ChainList[] table;
public HashMap(){
table = new ChainList [HASH_SIZE];
for(int i= 0 ; i < table.length; i++){
table[i] = null;
}
}
public int hashFunction(int key){
return (key%HASH_SIZE );
}
public int getElement(int key){
int index = hashFunction(key);
if(this.table[index] == null){
System.out.println("There isn't any element with that key!");
return -1;
}
else {
ChainList entry = table[index];
while (entry != null && entry.getKey() != key){
entry = entry.getNext();
}
if (entry == null){
return -1;
}
else{
System.out.println("I found an element with key: "+key+" and value: "+entry.getValue());
return entry.getValue();
}
}
}
public void put(int key,int value){
int index = hashFunction(key);
if(table[index] == null){
System.out.println("Adding new element into the Hash-Table");
table[index] = new ChainList(key,value);
}
else {
ChainList entry = table[index];
while (entry.getNext() != null && entry.getKey() != key){
entry = entry.getNext();
}
if (entry.getKey() == key){
entry.setValue(value);
}
else{
//Adding to the list because of the collision
entry.setNext(new ChainList(key, value));
}
}
}
public String toString(){
String s="";
for(int i=0;i<HASH_SIZE;i++){
if(table[i] != null){
System.out.println("inex : "+i);
s+="["+table[i].toString()+"]";
if(table[i].getNext() != null){
System.out.println("mpika");
ChainList entry = table[i].getNext();
while(entry != null ){
s+="-->"+entry.toString();
entry = entry.getNext();
}
}
s+="\n";
}
}
return s;
}
}