开发者

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

开发者 https://www.devze.com 2023-04-08 20:04 出处:网络
When I have collection, where each object is unique but they belong to some parentId, how should I store it?

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开发者_Go百科 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) ?


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;


Try using Guava's ListMultimap

ListMultimap<Integer, MyType> map = ArrayListMultimap.<Integer, MyType>create();

Then you can do:

List<MyType> children = map.get(parentId);


Yes; keep parent_id in MyType, where it belongs, or don't store it anywhere, and use the parent object's ID when you need it (it's unclear as worded what you're actually trying to accomplish).


HashMap<Integer, ArrayList<MyObject>> myObjects = new HashMap(); // Assuming parent_id is Integer

You can access it like this:

ArrayList<MyObject> myObjectsArray = myObjects.get(parent_id);
0

精彩评论

暂无评论...
验证码 换一张
取 消