Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Map with key only - for contains checking

Tags:

java

graph

map

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 .

Have you any better idea for this check using HashMap mode (O(1)) ?

like image 570
URL87 Avatar asked Nov 25 '12 07:11

URL87


1 Answers

A HashSet seems to be exactly what you need.

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. If you need an implementation that uses less memory, you could for instance have a look at this implementation.

like image 181
Aleksander Blomskøld Avatar answered Oct 23 '22 06:10

Aleksander Blomskøld