我必须为此存储一个关闭列表我定义了一个Map -
Map<Node, Boolean> closeList = new HashMap<Node, Boolean>()
现在用于检查此地图中是否存在节点我使用 -
boolean binExists = closeList .containsKey(node)
似乎地图的value-boolean
是不必要的。
您是否有更好的想法使用HashMap模式(O(1))进行此检查?
答案 0 :(得分:13)
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
即使使用Set<Node>
看起来比使用Map<Node, Boolean>
更好,java.util.HashSet
在其内部使用HashMap
实现。如果您需要使用较少内存的实现,您可以查看this implementation。
答案 1 :(得分:0)