6

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Map.getOrDefault is useful for this.
1

I concur with @Louis that the best solution is to check the result of the get call to see if it is null.

However, it is also possible to create a subclass of HashMap with an override for the get method that returns a default value if super.get(key) returns null. But beware of anomalies; e.g.

  • Iterating the map will give you only the entries that are "really there".

  • If there is a real entry with a null value (because you called put(key, null)) you won't get a null when you call get for the entries key. But but the entry will show up in the iteration ... with value null.

So, from an OO design perspective, a better approach (to extending HashMap) would be to create an application-specific class that only exposes a subset of the Map functionality.

Comments

1

Instead of explicitly putting Double.POSITIVE_INFINITY for all the possible keys (which may be inefficient), you can use putIfAbsent.

In any place where you have:

value = map.get(key);

you can change it to:

value = map.putIfAbsent(key,Double.POSITIVE_INFINITY);

This will behave as if the value of any key not present in the Map (or any key whose current value is null) is Double.POSITIVE_INFINITY. It will put the value Double.POSITIVE_INFINITY in the Map for any such keys.

It will save you the need to check if map.get(key) returns null.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.