Map order question

Penko

Active Member
Licensed User
Longtime User
Hi there!

I am trying to use a MAP to store objects for which it is from a great importance to keep ordered. The more I am trying, the more I realize maybe it's not what MAPs are about.

In my other topic I can't use WriteMap, ReadMap due to an error but I made a separate app to test things out.

B4X:
Sub Activity_Create(FirstTime As Boolean)


Dim map1 As Map
map1.Initialize
map1.Put("a","first item")
map1.Put("b","second item")
map1.Put("c","third item")

File.WriteMap(File.DirInternal, "storage.txt", map1)

Dim map2 As Map
map2.Initialize
map2.Put("a", "")
map2.Put("b", "")
map2.Put("c", "")

map2 = File.ReadMap2(File.DirInternal, "storage.txt", map2)

For i = 0 To map2.Size - 1

Dim a As String
a = map2.GetValueAt(i)
Msgbox(a, "AAAA")
Next

End Sub

The application runs correctly, everything is okay but the order I get my MsgBox-es is as follows:
- second item
- third item
- first item

I noticed there are m.Put("#Item1", "") commands which do the ordering trick.

But my items are dynamic?

It is more a question if it is possible(and how?) or I should go for another storage option.

By the way, I am recording the "ticks" when the item is added. Maybe it can be used for ordering purposes but anyway it won't happen with the single readMap/readMap2 commands and I will have to order the items myself.
 
Last edited:

Penko

Active Member
Licensed User
Longtime User
I am uploading two versions of the application.

The first one is "with_put" which features .Put commands on Map2 which do the sorting.

The second one is "without_put" which demonstrates how items are scrambled -> second -> third -> first.

My question was more a general one... What is the way to get my MAP objects sorted in the same way I have stored them? I've read your tutorial where you say that it is stated that the items can get out in a different way than the storing order.

So basically, should I use a MAP provided that my items are dynamic(added by users) and I store everything in a single storage.txt file via WriteMap?
 

Attachments

  • storing_with_put.zip
    5.5 KB · Views: 258
  • storing_without_put.zip
    5.5 KB · Views: 232
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
As stated in the documents the order of entries loaded by calling ReadMap is (more or less) random.

This is the reason that ReadMap2 was added.

In most cases the order is not important. If it is important to you and you cannot use ReadMap2 (with putting the keys in the correct order) then you should use a different method to store the items. You can for example store the items in a list instead of a map.
 
Upvote 0
Top