Sobes.tech
Middle

In Android, there are maps where you can add primitive types. Can you tell more about this?

sobes.tech AI

Answer from AI

Yes, for working with primitive types in Android SDK, there are specialized implementations of Map optimized for performance and memory efficiency compared to the standard HashMap<K, V>.

The most common ones are:

  • SparseIntArray: Stores pairs of int keys and int values.
  • SparseLongArray: Stores pairs of int keys and long values.
  • SparseBooleanArray: Stores pairs of int keys and boolean values.
  • LongSparseArray<E>: Stores pairs of long keys and objects of type E.

Advantages of using these classes:

  • Memory efficiency: They use internal arrays to store data, avoiding overhead associated with creating wrapper objects for primitive types (Integer, Long, Boolean) and the linked list structure of HashMap.
  • Performance: Insert, get, and delete operations are generally faster, especially with large numbers of elements, due to simpler internal structures and avoiding hashing for primitive keys in the case of SparseArray.

Example of using SparseIntArray:

// Creating SparseIntArray
SparseIntArray sparseArray = new SparseIntArray();

// Adding elements
sparseArray.put(0, 100);
sparseArray.put(1, 200);
sparseArray.put(10, 300);

// Getting value by key
int value = sparseArray.get(1); // value will be 200

// Getting value by key with default
int valueWithDefault = sparseArray.get(5, -1); // valueWithDefault will be -1

// Removing element by key
sparseArray.delete(10);

// Iterating over elements
for (int i = 0; i < sparseArray.size(); i++) {
    int key = sparseArray.keyAt(i);
    int val = sparseArray.valueAt(i);
    // Processing logic for key and val
}

Similarly, SparseLongArray, SparseBooleanArray, and LongSparseArray are used. LongSparseArray requires specifying the object type, as its values are objects, not primitives.

Choosing between the standard HashMap and specialized Sparse maps depends on your requirements:

  • If your keys are arbitrary objects or primitives other than int or long, use HashMap.
  • If your keys are int or long, and values are primitives or objects in the case of LongSparseArray, and memory efficiency and performance are important, prefer using Sparse maps.

Note that Sparse maps are not thread-safe. If you need a thread-safe implementation, consider using ConcurrentHashMap with wrapper objects for primitives. However, in most cases within the UI thread of an Android application, where these structures are often used, thread safety is not a concern.