1 /* 2 * Copyright (C) 2021 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.managedprovisioning.common; 18 19 import java.util.HashMap; 20 import java.util.Map; 21 import java.util.Objects; 22 23 /** 24 * A bi-directional map where the key and value are of the same type. 25 * 26 * @param <T> the type of the elements in this map 27 */ 28 public final class HomogenousBiMap<T> { 29 private final Map<T, T> mForwardMap = new HashMap<>(); 30 private final Map<T, T> mReverseMap = new HashMap<>(); 31 32 /** 33 * Puts an element to the map. 34 * 35 * @see #getForwardMap() 36 * @see #getReverseMap() 37 */ put(T key, T value)38 public void put(T key, T value) { 39 mForwardMap.put(key, value); 40 mReverseMap.put(value, key); 41 } 42 43 /** 44 * Returns a copy of the forward map. After {@link #put(Object, Object)} is called, the {@code 45 * key} is in the key set of this map, and the {@code value} is the value list of this map. 46 */ getForwardMap()47 public Map<T, T> getForwardMap() { 48 return new HashMap<>(mForwardMap); 49 } 50 51 /** 52 * Returns a copy of the reverse map. After {@link #put(Object, Object)} is called, the {@code 53 * value} is the key set of this map, and the {@code key} is the value list of this map. 54 */ getReverseMap()55 public Map<T, T> getReverseMap() { 56 return new HashMap<>(mReverseMap); 57 } 58 59 /** 60 * Clears the map. 61 */ clear()62 public void clear() { 63 mForwardMap.clear(); 64 mReverseMap.clear(); 65 } 66 67 @Override equals(Object o)68 public boolean equals(Object o) { 69 if (this == o) return true; 70 if (!(o instanceof HomogenousBiMap)) return false; 71 HomogenousBiMap<?> that = (HomogenousBiMap<?>) o; 72 return Objects.equals(mForwardMap, that.mForwardMap) && 73 Objects.equals(mReverseMap, that.mReverseMap); 74 } 75 76 @Override hashCode()77 public int hashCode() { 78 return Objects.hash(mForwardMap, mReverseMap); 79 } 80 } 81