class KeyValue val key val value class HashMap Null private val key va

 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
class KeyValue[K, V](val key: K, val value: V)
class HashMap[K, V>:Null] private (val key: K, val value: V, val oldtable: List[KeyValue[K, V]]) {
val pair = new KeyValue[K,V](key, value)
val newtable = pair :: oldtable
def this(key: K, value: V) = this(key, value, Nil);
def isEmpty() : String = newtable match {
case Nil => "yes"
case _ => "no"
}
private def existKey2(key: K, list: List[KeyValue[K, V]]) : Boolean = (key, list) match {
case (key, Nil) => false
case (key, x :: xs) if (x.key == key) => true
case (key, x :: xs) => existKey2(key, xs)
}
def existKey(key: K) : String = newtable match{
case Nil => "no"
case _ if (existKey2(key, newtable)) => "yes"
case _ => "no"
}
private def forGetValue(list: List[KeyValue[K, V]], key: K) : V = (list, key) match {
case (Nil, key) => null
case (x :: xs, key) if (x.key == key) => x.value
case (x :: xs, key) => forGetValue(xs, key)
}
def getValue(key: K) : V = {
forGetValue(newtable, key)
}
def insert(key: K, value: V) : HashMap[K, V] = {
if (existKey2(key, newtable)) this
else new HashMap(key, value, newtable)
}
private def deletePair(key: K, list: List[KeyValue[K, V]]) : List[KeyValue[K, V]] = (key, list) match {
case (key, Nil) => Nil
case (key, x :: xs) if (x.key == key) => deletePair(key, xs)
case (key, x :: xs) => x :: deletePair(key, xs)
}
def delete(key: K) : HashMap[K, V] = {
if (!existKey2(key, newtable)) this
else {
val x :: xs = deletePair(key, newtable)
new HashMap (x.key, x.value, xs)
}
}
}
val b = new HashMap(5,"asd")
val b2 = b.insert(8, "ewr")
val b3 = b2.insert(7, "ftp")
val b1 = b3.delete(5)
val c = b1.getValue(6)
val d = b1.isEmpty
val c1 = b1.getValue(7)
val e = b1.existKey(5)
val f = b1.existKey(8)
val h = b1.existKey(9)