What method should I use to keep items in a list if :
- I have a an object which contains a list of items and can do action on those items
- Those items are ordered inside a list
- I need to be able to change the position of items inside the list and add or remove an item based on its id.
- The list will be saved into a database eventually (and items will need to keep their order inside this list)
- It doesn’t make sense to have a property “order” on the orderd items (these objects can be in multiple kind of lists).
The choices that I have (is there any other choices?) :
- Use a List object so it will automatically keep the order. But I’ll have to loop through all objects (at worse) to find an object by Id.
- Use a map with a Key / Value (object id / object), so it’ll be easy to retrieve the object (and fast) and keep another map that just keeps the order of the object (object Id / object order)
Solution #1) This seems like the easiest solution with a performance drawback.
Solution #2) This seems like the fastest solution but with a lot more code when reordering list.
Is there an object that I don’t know about that would be ordered, have Key / Value pairs and have methods like object.add(index, key, value) or object.getByIndex(index) or object.getByKey(key)?
As
Ronisuggested you need to use your own data structure. I believe that is the only option viable to fill in your requirement.I have done a sample to fill in your requirement as a
starting pointand you can build on it.Hope this helps you….