1 /*
2  * Copyright (C) 2020 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 package com.android.internal.telephony;
18 
19 import android.util.ArrayMap;
20 
21 import java.util.Collection;
22 import java.util.Map;
23 
24 /**
25  * A very basic bidirectional map.
26  */
27 public class BiMap<K, V> {
28     private Map<K, V> mPrimaryMap = new ArrayMap<>();
29     private Map<V, K> mSecondaryMap = new ArrayMap<>();
30 
put(K key, V value)31     public boolean put(K key, V value) {
32         if (key == null || value == null || mPrimaryMap.containsKey(key) ||
33                 mSecondaryMap.containsKey(value)) {
34             return false;
35         }
36 
37         mPrimaryMap.put(key, value);
38         mSecondaryMap.put(value, key);
39         return true;
40     }
41 
remove(K key)42     public boolean remove(K key) {
43         if (key == null) {
44             return false;
45         }
46         if (mPrimaryMap.containsKey(key)) {
47             V value = getValue(key);
48             mPrimaryMap.remove(key);
49             mSecondaryMap.remove(value);
50             return true;
51         }
52         return false;
53     }
54 
removeValue(V value)55     public boolean removeValue(V value) {
56         if (value == null) {
57             return false;
58         }
59         return remove(getKey(value));
60     }
61 
getValue(K key)62     public V getValue(K key) {
63         return mPrimaryMap.get(key);
64     }
65 
getKey(V value)66     public K getKey(V value) {
67         return mSecondaryMap.get(value);
68     }
69 
getValues()70     public Collection<V> getValues() {
71         return mPrimaryMap.values();
72     }
73 
clear()74     public void clear() {
75         mPrimaryMap.clear();
76         mSecondaryMap.clear();
77     }
78 }
79