[英]Map with key only - for contains checking
I have to store a close list for this I defined a Map - 我必须存储一个关闭列表 ,我定义了一个地图 -
Map<Node, Boolean> closeList = new HashMap<Node, Boolean>()
now for checking whether a node is exist in this map I use - 现在用于检查此地图中是否存在节点我使用 -
boolean binExists = closeList .containsKey(node)
seems that the value-boolean
of the map is unnecessary . 似乎地图的value-boolean
是不必要的。
Have you any better idea for this check using HashMap mode (O(1)) ? 你有没有更好的想法使用HashMap模式(O(1))进行此检查?
A HashSet seems to be exactly what you need. 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
Even though using a Set<Node>
looks better than using a Map<Node, Boolean>
, java.util.HashSet
is using a HashMap
internally in it's implementation. 尽管使用Set<Node>
看起来比使用Map<Node, Boolean>
更好,但java.util.HashSet
在其实现中内部使用了HashMap
。 If you need an implementation that uses less memory, you could for instance have a look at this implementation . 如果您需要使用较少内存的实现,您可以查看此实现 。
With ArrayList you can get the following in O(1): 使用ArrayList,您可以在O(1)中获得以下内容:
With HashSet you can get the following in O(1): 使用HashSet,您可以在O(1)中获得以下内容:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.