Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing a HashMap with default values?

Tags:

java

I'm implementing the A* search algorithm given here, https://en.wikipedia.org/wiki/A*_search_algorithm

This line indicates we need to initiliaze a map with the default values of INFINITY,

gScore := map with default value of Infinity

So I tried that here,

Map<State, Double> gScore = new HashMap<State, Double>(Double.POSITIVE_INFINITY);

This does not work however the following does;

Map<State, Double> gScore = new HashMap<State, Double>((int) Double.POSITIVE_INFINITY);

I'm wondering why, and what impact (if any) it will have on my implementation.

like image 671
Talen Kylon Avatar asked Sep 26 '22 06:09

Talen Kylon


1 Answers

There is no way to initialize a map with a default value in Java, and your second version will not create a map with a default value of infinity, but instead will try to create an infinitely large map. (Not really, but it'll try creating the largest map possible.)

Instead, modify the algorithm: anytime you do map.get(key), check if the value is null and, if so, replace it with infinity.

like image 62
Louis Wasserman Avatar answered Oct 11 '22 23:10

Louis Wasserman