Junior
What are the implementations of collections in Java for Android?
sobes.tech AI
Answer from AI
In Android, standard implementations from the Java Collections Framework are available for working with collections, as well as specialized classes optimized for mobile devices with limited resources.
Main collection implementations:
- ArrayList — a dynamic array, good for quick access by index.
- LinkedList — a doubly linked list, efficient for frequent insertions and deletions.
- HashMap — a hash table for storing key-value pairs with fast access.
- SparseArray — a specialized implementation for storing pairs of int-keys and objects, more memory-efficient than HashMap<Integer, Object>, especially with a small number of elements.
- SparseBooleanArray, SparseIntArray, SparseLongArray — analogs of SparseArray for primitive types, saving memory.
Using SparseArray and its variants is recommended in Android, as they reduce the load on the garbage collector and save memory compared to regular HashMap, especially when working with primitive keys.
Example of using SparseArray:
SparseArray<String> sparseArray = new SparseArray<>();
sparseArray.put(1, "One");
sparseArray.put(2, "Two");
String value = sparseArray.get(1); // "One"
Thus, the choice of collection depends on the task and performance and memory requirements.