gpt4 book ai didi

java - LinkedHashSet 检索元素最有效的替代方案是什么?

转载 作者:行者123 更新时间:2023-12-02 07:03:58 25 4
gpt4 key购买 nike

现有的功能除了保留插入顺序之外,还使用 ​​LinkedHashSet 来存储一组唯一元素。

有一个新要求,要求检索 LinkedHashSet 中已存在的特定元素。即,当尝试添加元素时,该方法应检查该元素是否已存在并返回现有元素。 LinkedHashSet 中最多可以有 10000 个元素。

当前实现此目的的方法是在 LinkedHashSet 上使用迭代器

Class CustomObject {
String id;
String name;

CustomObject (String id, String name) {
this.id = id;
this.name = name;
}

LinkedHashMap<String, LinkedHashSet<CustomObject>> parentRecord = new LinkedHashMap<String, LinkedHashSet<CustomObject>>(4);
.
.
.
public CustomObject addCustomObject (CustomObject customObject)
//Assume the following child node not to be null
Set<CustomObject> child = parentRecord.get("customObjectName");

if (child.contains(customObject)) {
Iterator<CustomObject> it = child.iterator();
while (it.hasNext()) {
CustomObject node = it.next();
if (node.getId().equals(customObject.getId())) {
return node;
}
}
}

child.add(customObject);

return customObject;
}

}

有没有一种有效的替代数据结构方式

  1. 存储唯一值

  2. 尝试添加时如果特定元素已存在,则返回该元素

  3. 保留广告订单(如果可能)

Since the customObject being added is already in the set, returning the customObject itself makes sense.However, that somehow doesnt work hence went for iterator as I am building nodes within nodes. The customObject returned may have child nodes.

最佳答案

使用 LinkedHashMap<CustomObject, CustomObject>而不是 LinkedHashSet<CustomObject> .

(这假设 CustomObject.equalsCustomObject.hashcode 使用您当前的“匹配”方法。否则使用带有外部“哈希器”的第三方替代方法...)

该方法变为:

public CustomObject addCustomObject (CustomObject customObject) {
Map<CustomObject, Custom> child = parentRecord.get("customObjectName");

res = child.get(customObject);
if (res == null) {
child.put(customObject, customObject);
return customObject;
} else {
return res;
}
}

这应该都是O(1) .

关于java - LinkedHashSet 检索元素最有效的替代方案是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16317551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com