HashMap中的indexFor是如何计算的

HashMap中的indexFor方法分析

分析java7的HashMap源码的时候,其用indexFor来计算entry对象在table数组中的索引值

    static int indexFor(int h, int length) {
        // assert Integer.bitCount(length) == 1 : "length must be a non-zero power of 2";
        return h & (length-1);
    }

为什么不是对hash表的长度取余,而使用&进行位运算呢?

    /**
     * The table, resized as necessary. Length MUST Always be a power of two.
     */
    transient Entry<K,V>[] table = (Entry<K,V>[]) EMPTY_TABLE;

    /**
     * The default 
C中没有内置的HashMap数据结构,但可以使用一些技巧来实现类似的功能。一种常见的方法是使用哈希表(hash table)或关联数组(associative array)来HashMap。 在C中,你可以使用结构体和数组来创建自己的哈希表。下面是一个简单的示例: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #define SIZE 10 // 定义哈希节点结构体 typedef struct { char* key; int value; } HashNode; // 创建哈希表结构体 typedef struct { HashNode* nodes[SIZE]; } HashMap; // 哈希函数 int hashFunction(const char* key) { int sum = 0; for (int i = 0; i < strlen(key); i++) { sum += (int)key[i]; } return sum % SIZE; } // 初始化哈希表 void initHashMap(HashMap* hashMap) { for (int i = 0; i < SIZE; i++) { hashMap->nodes[i] = NULL; } } // 插入键值对到哈希表中 void insert(HashMap* hashMap, const char* key, int value) { int index = hashFunction(key); HashNode* newNode = (HashNode*)malloc(sizeof(HashNode)); newNode->key = strdup(key); newNode->value = value; hashMap->nodes[index] = newNode; } // 根据键查找值 int get(HashMap* hashMap, const char* key) { int index = hashFunction(key); HashNode* node = hashMap->nodes[index]; if (node != NULL && strcmp(node->key, key) == 0) { return node->value; } return -1; // 找不到返回-1 } int main() { HashMap hashMap; initHashMap(&hashMap); insert(&hashMap, "apple", 5); insert(&hashMap, "banana", 3); insert(&hashMap, "orange", 7); printf("Value for 'apple': %d\n", get(&hashMap, "apple")); printf("Value for 'banana': %d\n", get(&hashMap, "banana")); printf("Value for 'orange': %d\n", get(&hashMap, "orange")); return 0; } ``` 这个示例使用了一个简单的哈希函数,将键转换为索引值,并使用该索引将节点存储在哈希表的相应位置。insert函数将给定的键值对插入哈希表,get函数根据键查找对应的值。 请注意,这只是一个简单的示例,实际的哈希表实现可能需要更多的功能和更复杂的哈希函数,以提高性能和处理冲突等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值