LongLongHashMap.get should no longer throw NoSuchElementException
In many use cases it is more efficient to have a getter that returns a default value instead of throwing an exception. The exception forces every consumer to call containsKey() before calling get(). In cases where the consumer wants to use a default value this is unnecessary.
This commit is contained in:
@@ -1,10 +1,11 @@
|
||||
package org.lucares.collections;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/**
|
||||
* A hash map where key and value are primitive longs.
|
||||
*
|
||||
* @see LongObjHashMap
|
||||
*/
|
||||
public class LongLongHashMap {
|
||||
|
||||
@@ -125,21 +126,19 @@ public class LongLongHashMap {
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the value for the given key if it exists. This method throws a
|
||||
* {@link NoSuchElementException} if the key does not exist. Use
|
||||
* {@link #containsKey(long)} to check before calling {@link #get(long)}.
|
||||
* Returns the value for the given key if it exists or {@code defaultValue} if it does not exist.
|
||||
*
|
||||
* @param key the key
|
||||
* @return the value if it exists
|
||||
* @throws NoSuchElementException if the value does not exist
|
||||
* @param defaultValue the value to return if the given key does not exist
|
||||
* @return the value if it exists, or defaultValue
|
||||
*/
|
||||
public long get(final long key) {
|
||||
public long get(final long key, long defaultValue) {
|
||||
|
||||
if (key == NULL_KEY) {
|
||||
if (zeroValue != null) {
|
||||
return zeroValue;
|
||||
}
|
||||
throw new NoSuchElementException();
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
final int searchStart = spread(key);
|
||||
@@ -150,7 +149,7 @@ public class LongLongHashMap {
|
||||
}
|
||||
currentPosition = (currentPosition + 1) % keys.length;
|
||||
} while (currentPosition != searchStart);
|
||||
throw new NoSuchElementException();
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -206,7 +205,7 @@ public class LongLongHashMap {
|
||||
* <p>
|
||||
* The mapping for given key is updated by calling {@code function} with the old
|
||||
* value. The return value will be set as new value. If the map does not contain
|
||||
* a mapping for the key, then {@code function} is with
|
||||
* a mapping for the key, then {@code function} is called with
|
||||
* {@code initialValueIfAbsent}.
|
||||
*
|
||||
* @param key the key
|
||||
@@ -280,7 +279,7 @@ public class LongLongHashMap {
|
||||
for (int i = 0; i < sortedKeys.length; i++) {
|
||||
final long key = sortedKeys[i];
|
||||
if (key != EMPTY_SLOT) {
|
||||
consumer.accept(key, get(key));
|
||||
consumer.accept(key, get(key, 0)); // the default value of 'get' will not be used, because the key exists
|
||||
} else if (key == EMPTY_SLOT) {
|
||||
final int posFirstKey = findPosOfFirstPositiveKey(sortedKeys);
|
||||
if (posFirstKey < 0) {
|
||||
|
||||
Reference in New Issue
Block a user