Debian Codegraph @

core/java/android/view/accessibility/WeakSparseArray.java

raw symbols SCIP
1 /*
2 * Copyright (C) 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 android.view.accessibility;
18
19 import android.util.SparseArray;
20
21 import java.lang.ref.Reference;
22 import java.lang.ref.ReferenceQueue;
23 import java.lang.ref.WeakReference;
24
25
26 final class WeakSparseArray<E> {
27
28 private final ReferenceQueue<E> mRefQueue = new ReferenceQueue<>();
29 private final SparseArray<WeakReferenceWithId<E>> mSparseArray = new SparseArray<>();
30
31 public void append(int key, E value) {
32 removeUnreachableValues();
33 mSparseArray.append(key, new WeakReferenceWithId(value, mRefQueue, key));
34 }
35
36 public void remove(int key) {
37 removeUnreachableValues();
38 mSparseArray.remove(key);
39 }
40
41 public E get(int key) {
42 removeUnreachableValues();
43 WeakReferenceWithId<E> ref = mSparseArray.get(key);
44 return ref != null ? ref.get() : null;
45 }
46
47 private void removeUnreachableValues() {
48 for (Reference ref = mRefQueue.poll(); ref != null; ref = mRefQueue.poll()) {
49 mSparseArray.remove(((WeakReferenceWithId) ref).mId);
50 }
51 }
52
53 private static class WeakReferenceWithId<E> extends WeakReference<E> {
54
55 final int mId;
56
57 WeakReferenceWithId(E referent, ReferenceQueue<? super E> q, int id) {
58 super(referent, q);
59 mId = id;
60 }
61 }
62 }
63