Package com.carrotsearch.hppc
Class ObjectHashSet<KType>
- java.lang.Object
-
- com.carrotsearch.hppc.ObjectHashSet<KType>
-
- All Implemented Interfaces:
Accountable
,ObjectCollection<KType>
,ObjectContainer<KType>
,ObjectLookupContainer<KType>
,ObjectSet<KType>
,Preallocable
,java.lang.Cloneable
,java.lang.Iterable<ObjectCursor<KType>>
- Direct Known Subclasses:
ObjectIdentityHashSet
@Generated(date="2020-09-07T17:20:13+0200", value="KTypeHashSet.java") public class ObjectHashSet<KType> extends java.lang.Object implements ObjectLookupContainer<KType>, ObjectSet<KType>, Preallocable, java.lang.Cloneable, Accountable
A hash set ofObject
s, implemented using using open addressing with linear probing for collision resolution.- See Also:
- HPPC interfaces diagram
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description protected class
ObjectHashSet.EntryIterator
An iterator implementation foriterator()
.
-
Field Summary
Fields Modifier and Type Field Description protected int
assigned
The number of stored keys (assigned key slots), excluding the special "empty" key, if any.protected boolean
hasEmptyKey
Special treatment for the "empty slot" key marker.protected int
iterationSeed
Seed used to ensure the hash iteration order is different from an iteration to another.java.lang.Object[]
keys
The hash array holding keys.protected double
loadFactor
The load factor forkeys
.protected int
mask
Mask for slot scans inkeys
.protected int
resizeAt
-
Constructor Summary
Constructors Constructor Description ObjectHashSet()
New instance with sane defaults.ObjectHashSet(int expectedElements)
New instance with sane defaults.ObjectHashSet(int expectedElements, double loadFactor)
New instance with the provided defaults.ObjectHashSet(ObjectContainer<? extends KType> container)
New instance copying elements from anotherObjectContainer
.
-
Method Summary
All Methods Static Methods Instance Methods Concrete Methods Modifier and Type Method Description boolean
add(KType key)
Addsk
to the set.int
addAll(ObjectContainer<? extends KType> container)
Adds all elements from the givenObjectContainer
to this set.int
addAll(java.lang.Iterable<? extends ObjectCursor<? extends KType>> iterable)
Adds all elements from the given iterable to this set.int
addAll(KType... elements)
Adds all elements from the given list (vararg) to this set.protected void
allocateBuffers(int arraySize)
Allocate new internal buffers.protected void
allocateThenInsertThenRehash(int slot, KType pendingKey)
This method is invoked when there is a new key to be inserted into the buffer but there is not enough empty slots to do so.void
clear()
Removes all elements from this collection.ObjectHashSet<KType>
clone()
boolean
contains(KType key)
Lookup a given element in the container.void
ensureCapacity(int expectedElements)
Ensure this container can hold at least the given number of elements without resizing its buffers.boolean
equals(java.lang.Object obj)
protected boolean
equals(java.lang.Object v1, java.lang.Object v2)
<T extends ObjectProcedure<? super KType>>
TforEach(T procedure)
Applies aprocedure
to all container elements.static <KType> ObjectHashSet<KType>
from(KType... elements)
Create a set from a variable number of arguments or an array ofObject
.int
hashCode()
protected int
hashKey(KType key)
Returns a hash code for the given key.boolean
indexExists(int index)
KType
indexGet(int index)
Returns the exact value of the existing key.void
indexInsert(int index, KType key)
Inserts a key for an index that is not present in the set.int
indexOf(KType key)
Returns a logical "index" of a given key that can be used to speed up follow-up logic in certain scenarios (conditional logic).KType
indexReplace(int index, KType equivalentKey)
Replaces the existing equivalent key with the given one and returns any previous value stored for that key.boolean
isEmpty()
Shortcut forsize() == 0
.java.util.Iterator<ObjectCursor<KType>>
iterator()
Returns an iterator to a cursor traversing the collection.protected int
nextIterationSeed()
Provides the next iteration seed used to build the iteration starting slot and offset increment.long
ramBytesAllocated()
Allocated memory estimationlong
ramBytesUsed()
Bytes that is actually been usedprotected void
rehash(KType[] fromKeys)
Rehash from old buffers to new buffers.void
release()
Removes all elements from the collection and additionally releases any internal buffers.boolean
remove(KType key)
An alias for the (preferred)removeAll(KType)
.int
removeAll(ObjectLookupContainer<? super KType> c)
Default implementation uses a predicate for removal.int
removeAll(ObjectPredicate<? super KType> predicate)
Removes all elements in this collection for which the given predicate returnstrue
.int
removeAll(KType key)
Removes all occurrences ofe
from this collection.int
retainAll(ObjectLookupContainer<? super KType> c)
Default implementation uses a predicate for retaining.int
retainAll(ObjectPredicate<? super KType> predicate)
Default implementation redirects toObjectCollection.removeAll(ObjectPredicate)
and negates the predicate.protected void
shiftConflictingKeys(int gapSlot)
Shift all the slot-conflicting keys allocated to (and including)slot
.int
size()
Return the current number of elements in this container.java.lang.Object[]
toArray()
Default implementation of copying to an array.<T> T[]
toArray(java.lang.Class<T> componentClass)
Copies all elements of this container to a dynamically created array of the given component type.java.lang.String
toString()
Convert the contents of this container to a human-friendly string.protected double
verifyLoadFactor(double loadFactor)
Validate load factor range and return it.java.lang.String
visualizeKeyDistribution(int characters)
Visually depict the distribution of keys.-
Methods inherited from class java.lang.Object
finalize, getClass, notify, notifyAll, wait, wait, wait
-
Methods inherited from interface com.carrotsearch.hppc.ObjectCollection
removeAll, retainAll, retainAll
-
Methods inherited from interface com.carrotsearch.hppc.ObjectContainer
toArray
-
-
-
-
Field Detail
-
keys
public java.lang.Object[] keys
The hash array holding keys.
-
assigned
protected int assigned
The number of stored keys (assigned key slots), excluding the special "empty" key, if any.- See Also:
size()
,hasEmptyKey
-
mask
protected int mask
Mask for slot scans inkeys
.
-
resizeAt
protected int resizeAt
-
hasEmptyKey
protected boolean hasEmptyKey
Special treatment for the "empty slot" key marker.
-
loadFactor
protected double loadFactor
The load factor forkeys
.
-
iterationSeed
protected int iterationSeed
Seed used to ensure the hash iteration order is different from an iteration to another.
-
-
Constructor Detail
-
ObjectHashSet
public ObjectHashSet()
New instance with sane defaults.- See Also:
ObjectHashSet(int, double)
-
ObjectHashSet
public ObjectHashSet(int expectedElements)
New instance with sane defaults.- See Also:
ObjectHashSet(int, double)
-
ObjectHashSet
public ObjectHashSet(int expectedElements, double loadFactor)
New instance with the provided defaults.- Parameters:
expectedElements
- The expected number of elements guaranteed not to cause a rehash (inclusive).loadFactor
- The load factor for internal buffers. Insane load factors (zero, full capacity) are rejected byverifyLoadFactor(double)
.
-
ObjectHashSet
public ObjectHashSet(ObjectContainer<? extends KType> container)
New instance copying elements from anotherObjectContainer
.
-
-
Method Detail
-
add
public boolean add(KType key)
Addsk
to the set.
-
addAll
@SafeVarargs public final int addAll(KType... elements)
Adds all elements from the given list (vararg) to this set.- Returns:
- Returns the number of elements actually added as a result of this call (not previously present in the set).
-
addAll
public int addAll(ObjectContainer<? extends KType> container)
Adds all elements from the givenObjectContainer
to this set.- Returns:
- Returns the number of elements actually added as a result of this call (not previously present in the set).
-
addAll
public int addAll(java.lang.Iterable<? extends ObjectCursor<? extends KType>> iterable)
Adds all elements from the given iterable to this set.- Returns:
- Returns the number of elements actually added as a result of this call (not previously present in the set).
-
toArray
public java.lang.Object[] toArray()
Default implementation of copying to an array.- Specified by:
toArray
in interfaceObjectContainer<KType>
-
remove
public boolean remove(KType key)
An alias for the (preferred)removeAll(KType)
.
-
removeAll
public int removeAll(KType key)
Removes all occurrences ofe
from this collection.- Specified by:
removeAll
in interfaceObjectCollection<KType>
- Parameters:
key
- Element to be removed from this collection, if present.- Returns:
- The number of removed elements as a result of this call.
-
removeAll
public int removeAll(ObjectPredicate<? super KType> predicate)
Removes all elements in this collection for which the given predicate returnstrue
.- Specified by:
removeAll
in interfaceObjectCollection<KType>
- Returns:
- Returns the number of removed elements.
-
contains
public boolean contains(KType key)
Lookup a given element in the container. This operation has no speed guarantees (may be linear with respect to the size of this container).- Specified by:
contains
in interfaceObjectContainer<KType>
- Specified by:
contains
in interfaceObjectLookupContainer<KType>
- Returns:
- Returns
true
if this container has an element equal toe
.
-
clear
public void clear()
Removes all elements from this collection.- Specified by:
clear
in interfaceObjectCollection<KType>
- See Also:
ObjectCollection.release()
-
release
public void release()
Removes all elements from the collection and additionally releases any internal buffers. Typically, if the object is to be reused, a simpleObjectCollection.clear()
should be a better alternative since it'll avoid reallocation.- Specified by:
release
in interfaceObjectCollection<KType>
- See Also:
ObjectCollection.clear()
-
isEmpty
public boolean isEmpty()
Shortcut forsize() == 0
.- Specified by:
isEmpty
in interfaceObjectContainer<KType>
-
ensureCapacity
public void ensureCapacity(int expectedElements)
Ensure this container can hold at least the given number of elements without resizing its buffers.- Specified by:
ensureCapacity
in interfacePreallocable
- Parameters:
expectedElements
- The total number of elements, inclusive.
-
size
public int size()
Return the current number of elements in this container. The time for calculating the container's size may takeO(n)
time, although implementing classes should try to maintain the current size and return in constant time.- Specified by:
size
in interfaceObjectContainer<KType>
-
hashCode
public int hashCode()
- Overrides:
hashCode
in classjava.lang.Object
-
equals
public boolean equals(java.lang.Object obj)
- Overrides:
equals
in classjava.lang.Object
-
clone
public ObjectHashSet<KType> clone()
- Overrides:
clone
in classjava.lang.Object
-
iterator
public java.util.Iterator<ObjectCursor<KType>> iterator()
Returns an iterator to a cursor traversing the collection. The order of traversal is not defined. More than one cursor may be active at a time. The behavior of iterators is undefined if structural changes are made to the underlying collection.The iterator is implemented as a cursor and it returns the same cursor instance on every call to
Iterator.next()
(to avoid boxing of primitive types). To read the current list's value (or index in the list) use the cursor's public fields. An example is shown below.for (ObjectCursor<Object> c : container) { System.out.println("index=" + c.index + " value=" + c.value); }
- Specified by:
iterator
in interfacejava.lang.Iterable<KType>
- Specified by:
iterator
in interfaceObjectContainer<KType>
-
ramBytesAllocated
public long ramBytesAllocated()
Description copied from interface:Accountable
Allocated memory estimation- Specified by:
ramBytesAllocated
in interfaceAccountable
- Returns:
- Ram allocated in bytes
-
ramBytesUsed
public long ramBytesUsed()
Description copied from interface:Accountable
Bytes that is actually been used- Specified by:
ramBytesUsed
in interfaceAccountable
- Returns:
- Ram used in bytes
-
nextIterationSeed
protected int nextIterationSeed()
Provides the next iteration seed used to build the iteration starting slot and offset increment. This method does not need to be synchronized, what matters is that each thread gets a sequence of varying seeds.
-
forEach
public <T extends ObjectProcedure<? super KType>> T forEach(T procedure)
Applies aprocedure
to all container elements. Returns the argument (any subclass ofObjectProcedure
. This lets the caller to call methods of the argument by chaining the call (even if the argument is an anonymous type) to retrieve computed values, for example (IntContainer):int count = container.forEach(new IntProcedure() { int count; // this is a field declaration in an anonymous class. public void apply(int value) { count++; } }).count;
- Specified by:
forEach
in interfaceObjectContainer<KType>
-
forEach
public <T extends ObjectPredicate<? super KType>> T forEach(T predicate)
Applies apredicate
to container elements as long, as the predicate returnstrue
. The iteration is interrupted otherwise.- Specified by:
forEach
in interfaceObjectContainer<KType>
-
from
@SafeVarargs public static <KType> ObjectHashSet<KType> from(KType... elements)
Create a set from a variable number of arguments or an array ofObject
. The elements are copied from the argument to the internal buffer.
-
hashKey
protected int hashKey(KType key)
Returns a hash code for the given key.The output from this function should evenly distribute keys across the entire integer range.
-
indexOf
public int indexOf(KType key)
Returns a logical "index" of a given key that can be used to speed up follow-up logic in certain scenarios (conditional logic). The semantics of "indexes" are not strictly defined. Indexes may (and typically won't be) contiguous. The index is valid only between modifications (it will not be affected by read-only operations).- Parameters:
key
- The key to locate in the set.- Returns:
- A non-negative value of the logical "index" of the key in the set or a negative value if the key did not exist.
- See Also:
indexExists(int)
,indexGet(int)
,indexInsert(int, KType)
,indexReplace(int, KType)
-
indexExists
public boolean indexExists(int index)
- Parameters:
index
- The index of a given key, as returned fromindexOf(KType)
.- Returns:
- Returns
true
if the index corresponds to an existing key or false otherwise. This is equivalent to checking whether the index is a positive value (existing keys) or a negative value (non-existing keys). - See Also:
indexOf(KType)
-
indexGet
public KType indexGet(int index)
Returns the exact value of the existing key. This method makes sense for sets of objects which define custom key-equality relationship.- Parameters:
index
- The index of an existing key.- Returns:
- Returns the equivalent key currently stored in the set.
- Throws:
java.lang.AssertionError
- If assertions are enabled and the index does not correspond to an existing key.- See Also:
indexOf(KType)
-
indexReplace
public KType indexReplace(int index, KType equivalentKey)
Replaces the existing equivalent key with the given one and returns any previous value stored for that key.- Parameters:
index
- The index of an existing key.equivalentKey
- The key to put in the set as a replacement. Must be equivalent to the key currently stored at the provided index.- Returns:
- Returns the previous key stored in the set.
- Throws:
java.lang.AssertionError
- If assertions are enabled and the index does not correspond to an existing key.- See Also:
indexOf(KType)
-
indexInsert
public void indexInsert(int index, KType key)
Inserts a key for an index that is not present in the set. This method may help in avoiding double recalculation of the key's hash.- Parameters:
index
- The index of a previously non-existing key, as returned fromindexOf(KType)
.- Throws:
java.lang.AssertionError
- If assertions are enabled and the index does not correspond to an existing key.- See Also:
indexOf(KType)
-
visualizeKeyDistribution
public java.lang.String visualizeKeyDistribution(int characters)
Description copied from interface:ObjectSet
Visually depict the distribution of keys.- Specified by:
visualizeKeyDistribution
in interfaceObjectSet<KType>
- Parameters:
characters
- The number of characters to "squeeze" the entire buffer into.- Returns:
- Returns a sequence of characters where '.' depicts an empty fragment of the internal buffer and 'X' depicts full or nearly full capacity within the buffer's range and anything between 1 and 9 is between.
-
verifyLoadFactor
protected double verifyLoadFactor(double loadFactor)
Validate load factor range and return it. Override and suppress if you need insane load factors.
-
rehash
protected void rehash(KType[] fromKeys)
Rehash from old buffers to new buffers.
-
allocateBuffers
protected void allocateBuffers(int arraySize)
Allocate new internal buffers. This method attempts to allocate and assign internal buffers atomically (either allocations succeed or not).
-
allocateThenInsertThenRehash
protected void allocateThenInsertThenRehash(int slot, KType pendingKey)
This method is invoked when there is a new key to be inserted into the buffer but there is not enough empty slots to do so. New buffers are allocated. If this succeeds, we know we can proceed with rehashing so we assign the pending element to the previous buffer (possibly violating the invariant of having at least one empty slot) and rehash all keys, substituting new buffers at the end.
-
shiftConflictingKeys
protected void shiftConflictingKeys(int gapSlot)
Shift all the slot-conflicting keys allocated to (and including)slot
.
-
removeAll
public int removeAll(ObjectLookupContainer<? super KType> c)
Default implementation uses a predicate for removal.- Specified by:
removeAll
in interfaceObjectCollection<KType>
- Returns:
- Returns the number of removed elements.
-
retainAll
public int retainAll(ObjectLookupContainer<? super KType> c)
Default implementation uses a predicate for retaining.- Specified by:
retainAll
in interfaceObjectCollection<KType>
- Returns:
- Returns the number of removed elements.
-
retainAll
public int retainAll(ObjectPredicate<? super KType> predicate)
Default implementation redirects toObjectCollection.removeAll(ObjectPredicate)
and negates the predicate.- Specified by:
retainAll
in interfaceObjectCollection<KType>
- Returns:
- Returns the number of removed elements.
-
toArray
public <T> T[] toArray(java.lang.Class<T> componentClass)
Description copied from interface:ObjectContainer
Copies all elements of this container to a dynamically created array of the given component type.- Specified by:
toArray
in interfaceObjectContainer<KType>
-
toString
public java.lang.String toString()
Convert the contents of this container to a human-friendly string.- Overrides:
toString
in classjava.lang.Object
-
equals
protected boolean equals(java.lang.Object v1, java.lang.Object v2)
-
-