1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
15 # Highly specific, but useful, collections-related classes.
16 module more_collections
18 # Simple way to store an `HashMap[K, Array[V]]`
19 class MultiHashMap[K
: Object, V
]
20 super HashMap[K
, Array[V
]]
22 # Add `v` to the array associated with `k`.
23 # If there is no array associated, then create it.
24 fun add_one
(k
: K
, v
: V
)
26 if self.has_key
(k
) then
36 # Simple way to store an `HashMap[K1, HashMap[K2, V]]`
37 class HashMap2[K1: Object, K2: Object, V
]
38 private var level1
: HashMap[K1, HashMap[K2, V
]] = new HashMap[K1, HashMap[K2, V
]]
40 # Return the value associated to the keys `k1` and `k2`.
41 # Return `null` if no such a value.
42 fun [](k1
: K1, k2
: K2): nullable V
44 var level1
= self.level1
45 if not level1
.has_key
(k1
) then return null
46 var level2
= level1
[k1
]
47 if not level2
.has_key
(k2
) then return null
51 # Set `v` the value associated to the keys `k1` and `k2`.
52 fun []=(k1
: K1, k2
: K2, v
: V
)
54 var level1
= self.level1
55 var level2
: HashMap[K2, V
]
56 if not level1
.has_key
(k1
) then
57 level2
= new HashMap[K2, V
]
66 # Simple way to store an `HashMap[K1, HashMap[K2, HashMap[K3, V]]]`
67 class HashMap3[K1: Object, K2: Object, K3: Object, V
]
68 private var level1
: HashMap[K1, HashMap2[K2, K3, V
]] = new HashMap[K1, HashMap2[K2, K3, V
]]
70 # Return the value associated to the keys `k1`, `k2`, and `k3`.
71 # Return `null` if no such a value.
72 fun [](k1
: K1, k2
: K2, k3
: K3): nullable V
74 var level1
= self.level1
75 if not level1
.has_key
(k1
) then return null
76 var level2
= level1
[k1
]
80 # Set `v` the value associated to the keys `k1`, `k2`, and `k3`.
81 fun []=(k1
: K1, k2
: K2, k3
: K3, v
: V
)
83 var level1
= self.level1
84 var level2
: HashMap2[K2, K3, V
]
85 if not level1
.has_key
(k1
) then
86 level2
= new HashMap2[K2, K3, V
]