简体   繁体   中英

Efficient way to modify a list of objects using maps

I have a list of objects, these objects can shift position in the list or even be removed, this object that I am saving, each of them have an unique id, lets call this id "key". To quickly check membership in the list I have an additional map which is mapped as

<object.getKey(), object>

Currently I get a call to my method with this key, and I do a

map.contains(key)
// For delete
list.remove(map.get(key))
// For edit
Object oldObj = list.get(map.get(key))
// Modify the old obj, they are immutable so I need to set 
// old position with new object
list.set(map.get(key), newObject)

For sure this code is shit, but I am not able to wrap my head around a clean solution for this, I want to avoid any O(n) searches on the list which is clearly happening in the case of the list.remove and list.get!

One of the solutions I could think of was to map the key to the list position but then in case the map has a delete operation or an insert operation I'd have to update the whole map from the position of change! Again O(n). Any suggestions on the most efficient way to do this?

您尚未指定要使用列表的确切位置,但是假设您要查找具有可预测顺序的集合,请考虑使用LinkedHashSet它保留插入顺序,同时阶梯式允许addremovecontains在O(1)中。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM