简体   繁体   English

HashSet 与 Linked Hashset 的迭代

[英]Iteration through HashSet vs a Linked Hashset

I am thinking about ways to represent a graph in memory?我正在考虑在 memory 中表示图形的方法?

I was thinking to use a hash maps of hash maps so that it will behave similar to an adjacency matrix, but we can use Comparable edge labels instead of just integers.我正在考虑使用 hash 映射的 hash 映射,以便它的行为类似于邻接矩阵,但我们可以使用可比较边缘标签而不仅仅是整数。

In Breadth First Search and Dijkstra's algorithms, we have to iterate through adjacency lists and add nodes to the queue.在广度优先搜索和 Dijkstra 的算法中,我们必须遍历邻接列表并将节点添加到队列中。 This leads to my question:这导致了我的问题:

Is iteration through a linked hash set more efficient than iteration through a regular HashSet in Java?通过链接的 hash 集合进行迭代是否比通过 Java 中的常规 HashSet 进行迭代更有效?

It seems like it would be because there are links between each node in the order that they were added so we do not have to iterate through empty bins if they exist (depending on the re-hashing ratio of the HashMap, this could be more or less).似乎是因为每个节点之间的链接按添加顺序排列,所以如果它们存在,我们不必遍历空箱(取决于 HashMap 的重新散列率,这可能更多或较少的)。 This would allow us to combine the random access behavior of the adjacency matrix with the search algorithm efficiency of the adjacency list.这将允许我们将邻接矩阵的随机访问行为与邻接列表的搜索算法效率结合起来。

Yes, you're right.你是对的。

Java HashMap/Set has poor performance in sparse graph, because it must iterator from empty bins. Java HashMap/Set 在稀疏图中的性能很差,因为它必须从空 bin 进行迭代。 When most of nodes only connected one other node.当大多数节点只连接一个其他节点时。 The HashMap/Set maybe take 8 iteration to get the exact result. HashMap/Set 可能需要 8 次迭代才能得到准确的结果。 The related analysis could be found in Codeforces: Performance of hash set iterators in different programming languages .相关分析见Codeforces:Performance of hash set iterators in different programming languages

In order to represent graph, Java generic mechanism may let you create Object type for primitive type, like Integer.为了表示图形,Java 泛型机制可以让您为原始类型创建 Object 类型,例如 Integer。 They will slow down performance when convert to primitive type and build graph.当转换为原始类型并构建图形时,它们会降低性能。 In best practice, you need to use Trove or other library.在最佳实践中,您需要使用Trove或其他库。 Perhaps, implement by yourself.也许,自己实施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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