Search code examples
javaandroidcollectionshas-manybelongs-to

How to save objects in list without unique ID (belongsTo, hasMany)


When I have collection, where each object is unique but they belong to some parentId, how should I store it?

My Idea is

  • ArrayList <MyType> objects_list; // to store those objects
  • ArrayList <int[]> parents_list // to store parent_id vs int[] object_list.id's

So connection would be

  • object_list.item belongsTo parents_list.item
  • parents_list.item hasMany object_list.item

Isn't there some more efficient, more Java, solution?


Little more explain:

I have collection of object, where every object has parent_id in some variable within.
I need to store those objects, so that I could easily select all objects by their parent_id

And I cannot use simple one ArrayList with parent_id as key, because key has to be unique.

So how to store them, to fetch all objects by their parent_id like Collection.getByParentId(parent_id) ?


Solution

  • Like Dave said before, store the parent ID in MyType.

    // all MyType objects
    List<MyType> objects;
    
    // This way you could track the relations
    // (you would have to update this on change)
    Map<Integer, List<MyType>> relations;