What is a key object (use in hashmap)?

Can someone explain what exactly is the key object to use in hashmap? There is a method: "put (object key, object value) Associates the specified value with the specified key on this map."

so the key is any object you want? And by value, they mean another object or as an attribute. Just need some explanation, since I'm confused! Thanks a bunch

+4
source share
3 answers

You should read what hashmap is . In general, a hash is a data structure for efficient storage of arbitrary data (values ) in the table.

A common problem with storing information in any structure is how to quickly search for data again once it is in the structure. The hash solves this problem using keys . The value key determines where in the table the value will be stored using some hash function . They are used in the hash in the same way as the index used in the array:

array[index] => some_value hash{key} => some_value 

In the case of "put (Object key, Object value)", the "value" object is the data that you want to save, and the "key" object is what you will use to output data from the hash:

 MyObject myKey = new MyObject( ... ); MyOtherObject myValue = new MyOtherObject( ... ); ... myHash.put( myKey, myValue ); // add myValue to the hash ... MyOtherObject data = myhash.get( myKey ); // get myValue out of the hash 
+2
source

so the key is any object you want?

Generally speaking, yes.

However, you need to be careful in implementing the objects that you use as keys on the map. They must be immutable and override equals() and hashCode() .

0
source

The key must be something that does not change (a lot) over time, is unique (within this Card) and has some significant connection with the value. For example, SSN, name, license plate, or zip code. But basically everything that makes sense to you.

0
source

Source: https://habr.com/ru/post/1383696/


All Articles