From 928bb445efe0a1c27b950dad4de749c705b0c346 Mon Sep 17 00:00:00 2001 From: Kweku Adams Date: Wed, 14 Sep 2022 16:37:45 +0000 Subject: [PATCH] Return the previous value when adding a new one. It would be nice to be able to get the previous value when adding a new one without having to do a separate get() call. Bug: 243987091 Test: atest CtsUtilTestCases:SparseArrayMapTest Change-Id: I763c08443b9376f5142abd1aa817f1c61990f4be --- core/api/test-current.txt | 2 +- core/java/android/util/SparseArrayMap.java | 12 +++++++++--- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/core/api/test-current.txt b/core/api/test-current.txt index deb5aca53b78d..f780e6f3b39b5 100644 --- a/core/api/test-current.txt +++ b/core/api/test-current.txt @@ -2709,7 +2709,7 @@ package android.util { public class SparseArrayMap { ctor public SparseArrayMap(); - method public void add(int, @NonNull K, @Nullable V); + method public V add(int, @NonNull K, @Nullable V); method public void clear(); method public boolean contains(int, @NonNull K); method public void delete(int); diff --git a/core/java/android/util/SparseArrayMap.java b/core/java/android/util/SparseArrayMap.java index e5bb9f453a889..1a2c4df96b367 100644 --- a/core/java/android/util/SparseArrayMap.java +++ b/core/java/android/util/SparseArrayMap.java @@ -34,14 +34,20 @@ import java.util.function.Consumer; public class SparseArrayMap { private final SparseArray> mData = new SparseArray<>(); - /** Add an entry associating obj with the int-K pair. */ - public void add(int key, @NonNull K mapKey, @Nullable V obj) { + /** + * Add an entry associating obj with the int-K pair. + * + * @return the previous value associated with key, or null if there was no mapping for key. + * (A null return can also indicate that the map previously associated null with key, if the + * implementation supports null values.) + */ + public V add(int key, @NonNull K mapKey, @Nullable V obj) { ArrayMap data = mData.get(key); if (data == null) { data = new ArrayMap<>(); mData.put(key, data); } - data.put(mapKey, obj); + return data.put(mapKey, obj); } /** Remove all entries from the map. */