1 /*
2  * Copyright 2019 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.car.messenger.common;
18 
19 import java.util.Map;
20 import java.util.Objects;
21 
22 /**
23  * A composite key used for {@link Map} lookups, using two strings for
24  * checking equality and hashing.
25  */
26 public abstract class CompositeKey {
27     private final String mDeviceId;
28     private final String mSubKey;
29 
CompositeKey(String deviceId, String subKey)30     protected CompositeKey(String deviceId, String subKey) {
31         mDeviceId = deviceId;
32         mSubKey = subKey;
33     }
34 
35     @Override
equals(Object o)36     public boolean equals(Object o) {
37         if (this == o) {
38             return true;
39         }
40 
41         if (!(o instanceof CompositeKey)) {
42             return false;
43         }
44 
45         CompositeKey that = (CompositeKey) o;
46         return Objects.equals(mDeviceId, that.mDeviceId)
47                 && Objects.equals(mSubKey, that.mSubKey);
48     }
49 
50     /**
51      * Returns true if the device address of this composite key equals {@code deviceId}.
52      *
53      * @param deviceId the device address which is compared to this key's device address
54      * @return true if the device addresses match
55      */
matches(String deviceId)56     public boolean matches(String deviceId) {
57         return mDeviceId.equals(deviceId);
58     }
59 
60     @Override
hashCode()61     public int hashCode() {
62         return Objects.hash(mDeviceId, mSubKey);
63     }
64 
65     @Override
toString()66     public String toString() {
67         return String.format("%s, deviceId: %s, subKey: %s",
68                 getClass().getSimpleName(), mDeviceId, mSubKey);
69     }
70 
71     /** Returns this composite key's device address. */
getDeviceId()72     public String getDeviceId() {
73         return mDeviceId;
74     }
75 
76     /** Returns this composite key's sub key. */
getSubKey()77     public String getSubKey() {
78         return mSubKey;
79     }
80 }
81