0

In a Java application I need an structure to store, lets call them nodes, and the number of relationship with other nodes. For example, I would need to know that node A is related with B 3 times.

Thinking in a way to implement this I got to this possible solution: Have a hashmap using nodes as key and another hashmap as value. This hashmap would store nodes as key (node B in the example) and an integer as value representing the number of relationships.

What do you think about this? Is it a good approach?

If so, I have a question. Suppose tha I store strings and they come from a text file after apply String.split function. Now I store "hello" in the first hashmap but after processing the file, this string appears as a destiny node in the second hashmap. Would these strings have a reference to the same object or I'll have multiple copies of the same objects?

4

1 回答 1

1

关于第一个问题,我会做一些类似但不同的事情。我不会创建一个Hashmapinside aHashmap我会创建一个Relationship看起来像这样的新类:

public class NodeRelationship {
    private Node relatedNode;
    private int numOfRelations

    // Constructor + getters and setters
}

并像这样定义您的地图:Map<Node, List<NodeRelationship>>这对我来说似乎更具可读性(但也许只是我自己)并且以后更容易扩展。例如,如果您在列表上进行迭代并想知道原始节点,您可以添加一个成员parentNodeRelationshio依此类推。

关于第二个问题 - 这取决于您如何创建对象以及您是创建新对象还是使用现有对象。如果您有一个节点hello,您输入了您的值Hashmap(或在List我的解决方案中),并且您使用相同的对象来创建新密钥 - 所以没有重复。如果您没有办法(或只是不搜索)知道节点已经创建,并且您创建了新节点 - 那么您将拥有重复的对象。

如果确实您的每个节点都是从文本字符串创建的,则可以维护一个新节点,Map<String, Node>并且在读取文件的过程中您可以维护此映射并在创建新对象之前检查对象是否存在。这是非常低的性能成本,一旦从文本构建对象,您就可以摆脱地图。

于 2013-10-10T08:52:10.967 回答