简体   繁体   English

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

[英]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)中获得以下内容:

  • size 尺寸
  • isEmpty 是空的
  • get 得到
  • set
  • iterator 迭代器
  • listIterator 的ListIterator

With HashSet you can get the following in O(1): 使用HashSet,您可以在O(1)中获得以下内容:

  • add
  • remove 去掉
  • contains 包含
  • size 尺寸

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

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