-3

JavaのHashMapでは、ハッシュ値がバケットに格納されることを理解しました。これは、検索の高速化に役立ちます。
取得中に、ハッシュコードをチェックし、それに応じてバケット番号を見つけます。

1から10までのバケット番号があり、ハッシュコードから見つかったバケット番号がバケット番号5である場合

コントロールはどのようにバケット番号5に転送されますか?バケット1を通過してバケット4に到達して5に到達しますか、それとも他のメカニズムを使用しますか?

4

5 に答える 5

6

直接配列アクセスです。反復/トラバーサルなし。ただし、バケットのオブジェクトをトラバースし、 と比較する必要がありますequals。多分それはあなたを混乱させています。

于 2012-04-16T11:42:03.290 に答える
5

ハッシュ テーブルはバケットの配列として実装されるため、配列のランダム アクセスインデックスを使用して、ハッシュが与えられた適切なバケットに到達します。

于 2012-04-16T11:42:17.313 に答える
3

ハッシュ関数を使用してバケットを見つけます。

10 個のバケットがある場合、たとえば文字列のセットについて、文字値が追加され、10 個のバケットにハッシュされるとします。

文字列を 10 個のバケットにマップする簡単なハッシュ関数を書きましょう。

 For any non empty String, 

             hash function f = sum of (index of characters) % 10

例: abc = 1+2+3 %10 = 6. したがって、「abc」は 6 番目のバケットになります。xyz = 24+25+25 %10 = 7.5~ 8 . したがって、「xyz」は 8 番目のバケットなどになります。

したがって、「xyz」を検索すると、ハッシュ関数はここでバケットを直接見つけます。

ハッシュ関数は、ハッシュ マップの作業の中心です。

于 2012-04-16T11:46:53.160 に答える
2

java.util.HashMap コードからの抜粋

         /**
          * Adds a new entry with the specified key, value and hash code to
          * the specified bucket.  It is the responsibility of this
          * method to resize the table if appropriate.
          *
          * Subclass overrides this to alter the behavior of put method.
          */
         void addEntry(int hash, K key, V value, int bucketIndex) {
             Entry<K,V> e = table[bucketIndex];
             table[bucketIndex] = new Entry<>(hash, key, value, e);
             if (size++ >= threshold)
                 resize(2 * table.length);
         }

したがって、配列からランダムにアクセスされます。

于 2012-04-16T11:46:26.350 に答える
0

There are several strategies while adding and retrieving the values some of them are direct chaning, open addressing etc Based on these the way it stores and fetching values will change.For example, in direct chaining each space of bucket array is pointer to a linked list that contains the key-value pairs that hashed to the same location.So when you search the value, it is scanning the entire list with the give value.

于 2012-04-16T11:57:25.043 に答える