TheAlgorithms/Java · error · IllegalArgumentException
Key already exists; duplicates are not allowed.
Error message
Key already exists; duplicates are not allowed.
What it means
Thrown by `HashMapCuckooHashing.insertKey2HashTable` when the key is already present. Cuckoo hashing stores each key in exactly one of two possible buckets, so a duplicate would violate that invariant; the insert method checks `checkTableContainsKey(key)` before placing the key and refuses duplicates.
Source
Thrown at src/main/java/com/thealgorithms/datastructures/hashmap/hashing/HashMapCuckooHashing.java:85
* it into its alternate location. If the insertion process exceeds the threshold,
* the table is resized.
*
* @param key the key to be inserted into the hash table
* @throws IllegalArgumentException if the key already exists in the table
*/
public void insertKey2HashTable(int key) {
Integer wrappedInt = key;
Integer temp;
int hash;
int loopCounter = 0;
if (isFull()) {
System.out.println("Hash table is full, lengthening & rehashing table");
reHashTableIncreasesTableSize();
}
if (checkTableContainsKey(key)) {
throw new IllegalArgumentException("Key already exists; duplicates are not allowed.");
}
while (loopCounter <= thresh) {
loopCounter++;
hash = hashFunction1(key);
if ((buckets[hash] == null) || Objects.equals(buckets[hash], emptySlot)) {
buckets[hash] = wrappedInt;
size++;
checkLoadFactor();
return;
}
temp = buckets[hash];
buckets[hash] = wrappedInt;
wrappedInt = temp;
hash = hashFunction2(temp);
if (Objects.equals(buckets[hash], emptySlot)) {View on GitHub (pinned to fdfb9a395b)
Solutions
- Check `checkTableContainsKey(key)` before inserting
- De-duplicate input data upstream
- Treat re-insertion as a no-op by guarding with a contains check
Example fix
// before
map.insertKey2HashTable(k);
// after
if (!map.checkTableContainsKey(k)) {
map.insertKey2HashTable(k);
} Defensive patterns
Strategy: validation
Validate before calling
if (!map.checkTableContainsKey(key)) {
map.insertKey2HashTable(key);
} Try / catch
try {
map.insertKey2HashTable(key);
} catch (IllegalArgumentException e) {
// key already present
} Prevention
- Guard inserts with a contains check for idempotent pipelines
- De-duplicate source data before bulk insertion
When it happens
Trigger: Calling `insertKey2HashTable(k)` twice with the same `k`, or inserting a key that an earlier insert/rehash already stored.
Common situations: Re-ingesting the same records in a pipeline; idempotency not handled at the caller; re-insertion after a failed delete.
Related errors
- Table is empty, cannot delete.
- Key {key} not found in the table.
- Table is empty; cannot find keys.
- Input array cannot be null
- Key must contain each position exactly once
AI-assisted analysis of TheAlgorithms/Java@fdfb9a395b (2026-08-13).
Data as JSON: /api/errors/39ec92780511d055.
Report an issue: GitHub.