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 objectsArrayList <int[]> parents_list
// to storeparent_id
vsint[] 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.
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);
精彩评论