如何将基于int键的HashMap修改为使用long类型键?
Switching HashMap Key Type from
int to long for Large CSV Keys Got it, let's walk through how to safely update your HashMap implementation to use long keys instead of int—without breaking your already-working probe logic or CSV parsing. Here's a step-by-step breakdown tailored to your setup:
1. Update the HashEntry Class
First, adjust the core entry class to store a long key instead of int:
class HashEntry { // Replace int with long for the key field long key; String[] value; // Update constructor to accept long key public HashEntry(long key, String[] value) { this.key = key; this.value = value; } // Keep other existing methods (like equals checks) unchanged—long equality works the same as int }
2. Modify the HashMap Class Core Logic
Next, update all key-related references in your HashMap implementation:
- Adjust method signatures: Change
put(int key, String[] value)toput(long key, String[] value)andget(int key)toget(long key). - Update the hash function: Long values have 64 bits, so you'll want to mix both high and low 32-bit segments to avoid poor hash distribution. A simple, effective approach is:
private int hash(long key) { // Use Long's built-in hashCode to handle 64-bit mixing, then mod by capacity return Long.hashCode(key) % capacity; // Alternatively, manual mixing: return (int)(key ^ (key >>> 32)) % capacity; } - Verify probe logic: Your linear/standard/quadratic probe code should work as-is—just ensure all key comparisons (
entry.key == key) are still using long values (no type mismatches here).
3. Fix CSV Parsing Code
Update how you read the first column of your CSV to parse as long instead of int:
// When processing each CSV row String keyStr = csvRow[0]; long key; try { // Replace Integer.parseInt with Long.parseLong key = Long.parseLong(keyStr); } catch (NumberFormatException e) { // Handle invalid key values (e.g., skip the row or log an error) System.err.println("Skipping row - invalid long key: " + keyStr); continue; } // Now pass the long key to your HashMap's put method yourHashMap.put(key, Arrays.copyOfRange(csvRow, 1, csvRow.length));
4. Test Edge Cases
Don't forget to validate with edge-case keys to ensure everything works:
- Keys larger than
Integer.MAX_VALUE(e.g.,2147483648) - Keys smaller than
Integer.MIN_VALUE(e.g.,-2147483649) - Extreme long values like
Long.MAX_VALUEandLong.MIN_VALUE - Duplicate keys to confirm your probe logic still resolves conflicts correctly
内容的提问来源于stack exchange,提问作者Chris Chance
相关产品推荐
相关产品推荐

