This repository has been archived by the owner on Sep 14, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HashMapp.java
98 lines (87 loc) · 2.1 KB
/
HashMapp.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
package com.hkt.tutorial.algorithms.ds;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HashMapp<K, V> implements Map<K, V> {
private int size;
private HashMapp.Entry<K, V>[] array;
public HashMapp(int size) {
array = new HashMapp.Entry[size];
size = 0;
}
@Override
public int size() {
return size;
}
@Override
public boolean contains(K key) {
int index = hash(key);
Entry<K, V> e = array[index];
while (e != null) {
if (e.getKey().equals(key)) {
return true;
}
e = e.getNext();
}
return false;
}
@Override
public V get(K key) {
int index = hash(key);
Entry<K, V> er = array[index];
while (er != null) {
if (er.getKey().equals(key)) {
return er.getValue();
}
er = er.getNext();
}
return null;
}
@Override
public V put(K key, V value) {
int index = hash(key);
Entry entry = new Entry(key, value);
if (array[index] == null) {
array[index] = entry;
} else {
Entry current = array[index];
while (current != null) {
if (current.getKey().equals(entry.getKey())) {
current.setValue(entry.getValue());
return (V) current.getValue();
}
current = current.getNext();
}
current.setNext(entry);
}
size++;
return null;
}
@Override
public V remove(K key) {
int index = hash(key);
Entry entry = null;
Entry current = array[index];
while (current != null) {
if (current.getKey().equals(key)) {
if (entry != null)
entry.setNext(current.getNext());
else
array[index] = current.getNext();
size--;
return (V) current.getValue();
}
entry = current;
current = current.getNext();
}
return null;
}
@Override
public void clear() {
for (int i = 0; i < array.length; i++) {
array[i] = null;
}
size = 0;
}
public int hash(K key) {
return Math.abs(key.hashCode() % array.length);
}
}