仅使用密钥映射 - 用于包含检查

URL*_*L87 7 java graph map

我必须存储一个关闭列表,我定义了一个地图 -

Map<Node, Boolean> closeList = new HashMap<Node, Boolean>()

现在用于检查此地图中是否存在节点我使用 -

boolean binExists = closeList .containsKey(node)

似乎value-boolean地图的位置是不必要的.

你有没有更好的想法使用HashMap模式(O(1))进行此检查?

Ale*_*øld 15

一个HashSet的似乎正是你需要的.

Set<Node> closeSet = new HashSet<>();
Node n1 = new Node();
Node n2 = new Node();
closeSet.add(n1);
System.out.println(closeSet.contains(n1)); //true
System.out.println(closeSet.contains(n2)); //false - though depending upon equals/hashcode implementation of Node
Run Code Online (Sandbox Code Playgroud)

即使使用Set<Node>看起来比使用a更好Map<Node, Boolean>,在其实现中java.util.HashSet使用HashMap内部.如果您需要使用较少内存的实现,您可以查看此实现.