Tell me, please, an array, a container, anything, which will store data in the "key, value" format, and accordingly search by this key. The key will be Long and will store the date (day, month, year, the rest zeros). Value - The object of a particular class. The meaning is to read information as a date as quickly as possible, rather than looping through the entire array. I searched the Internet, found SparceArray, but I couldn’t correctly write it to Parcelable. There is a writeSparseArray procedure that accepts a SparseArray val as input, but I could not make friends with them.
3 answers
And why can not do this:
Map<Long, SomeObject> data = new HashMap<Long, SomeObject>;
and get value data.get('keyValue')
? The key is needed to get exactly the object that corresponds to the key.
What do you need to do?
- The fact is that Android Studio strongly recommends that I use the SparceArray class, referring to the fact that it is an alternative to the Map class and its derivative. But there are almost no examples of this class in the internet - Arsen Shogenov
- @ ArsenShogenov studio is such a studio. I propose to pretend that you do not notice this proposal. - rjhdby
- What is the maximum number of objects will lie in the container? SparseArray has a get method (int key) that does the same thing as HashMap / - JAVAvladuxa
- Thank you for your help! - Arsen Shogenov
|
Use LongSparceArray . In this structure, access by key will occur in constant time. Insertion is also carried out quickly.
Usage is:
LongSparseArray<YourObject> yourArray = new LongSparseArray(); // если ключи будут поступать в произвольном порядке yourArray.put(key, typeOfPayment); // если ключи будут поступать по возрастанию yourArray.append(key, typeOfPayment); //доступ yourArray.get(key);
If the size of the array is known in advance, then this size can be passed through the constructor.
- I learned this, but I could not save an instance in Parcelable using writeSparseArray. I do not find any examples on the Internet - Arsen Shogenov
|
Not that?
HashMap newmap = new HashMap(); ......... List list.addAll(newmap.keySet()); if (lista.contains(myKey)) { ..... }
- Why is there a list at all? - Vladyslav Matviienko
- @metalurgus for .contains. With the native Set you will have to fence the search in the loop, which the author wanted to avoid - rjhdby
- No, I do not have to.
Map
hascontainsKey
- Vladyslav Matviienko - @metalurgus cort. After all, the truth. - rjhdby
|
Map
. not necessarilyHashMap
- Vladyslav Matviienko