org.jgroups.util.IntHashMap Maven / Gradle / Ivy
Go to download
This artifact provides a single jar that contains all classes required to use remote EJB and JMS, including
all dependencies. It is intended for use by those not using maven, maven users should just import the EJB and
JMS BOM's instead (shaded JAR's cause lots of problems with maven, as it is very easy to inadvertently end up
with different versions on classes on the class path).
package org.jgroups.util;
import java.util.Arrays;
import java.util.Objects;
import java.util.StringJoiner;
/**
* A hashmap where keys have to be ints. The size is fixed and keys/values are stored in a simple array, e.g.
* [K1,V1, K2,V2, ... Kn,Vn]. The keys are indices into the array.
* Typically populated at startup and then used in read-only mode. This implementation is unsynchronized, and keys
* and values have to be non-null. Note that removals and changes (e.g. adding the same key twice) are unsupported.
* Note that this class does not lend itself to be used as a sparse array, ie. adding keys [0 .. 100] and then 5000
* would create an array of length 5001, and waste the space between index 100 and 5000. Ideally, keys start as 0, so
* adding keys [50..100] would also waste the space for 50 keys.
* @author Bela Ban
* @since 5.0.0
*/
public class IntHashMap {
protected T[] table;
protected int size;
/**
* Creates an instance
* @param highest_key The key with the highest value. The underlying array will be sized as highest_key+1
*/
public IntHashMap(int highest_key) {
table=(T[])new Object[Util.nonNegativeValue(highest_key)+1];
}
public int getCapacity() {return table.length;}
public int size() {return size;}
public boolean isEmpty() {return size == 0;}
public boolean containsKey(int k) {return k+1 <= table.length && table[k] != null;}
public T get(int k) {return k +1 <= table.length? table[k] : null;}
public IntHashMap put(int key, T value) {
checkCapacity(key);
T val=table[key];
if(val != null)
throw new IllegalStateException(String.format("duplicate key %d (value: %s)", key, val));
table[key]=Objects.requireNonNull(value);
size++;
return this;
}
public String toString() {
StringJoiner sj=new StringJoiner(", ", "{", "}");
for(int i=0; i < table.length; i++) {
T el=table[i];
if(el != null)
sj.add(i + "=" + el.toString());
}
return sj.toString();
}
protected IntHashMap checkCapacity(int key) {
if(key+1 > table.length) {
int new_len=key+1;
table=Arrays.copyOf(table, new_len);
}
return this;
}
}