-1

I have read up quite a bit on these and am still rather confused on one aspect. HashMaps take in a K,V pair. Why is this necessary?

For example I want to add "abracadabra" to HashMap myMap.

Would it not use String.hashCode() function as the key, and then "abracadabra" as the value?

And then if I were trying to lookup if "abracadabra" is there it would check if the 'bucket' for that hashCode is nonempty, and if it is then iterate through everything in that 'bucket' (At worst O(n)...but not in reality). So what I am saying is wouldn't the objects .hashCode() function be the key and the object is the hashcode? Why is an explicit Key necessary to be declared?

What is the purpose of having K,V pair? I have had this explained to me multiple times and have read multiple articles/examples/etc. and I still can't get it through my thick skull.

Dax Durax
  • 1,607
  • 5
  • 23
  • 31

4 Answers4

0

A hashmap is a mapping from key (in your case abracadabra) to an object. This is useful if you get the key from somewhere else, e.g. an id identifying an user and you need to load additional data for that user.

What you described sounds more like a HashSet

Ulrich Dangel
  • 4,515
  • 3
  • 22
  • 30
0

You are looking a the wrong object: HashMaps are not ment to store a single object (e.g. the string "abracadabra"), they are indeed ment to store key-value pairs, where both parts are of importance - an easy example would be a property store: The property name is the key, the property value the value.

If you want to really store just one object, look at other structures. HashSet comes to mind.

Eugen Rieck
  • 64,175
  • 10
  • 70
  • 92
  • So is hashmap basically a hashset of containers? (in your example holding the name and value of property) – Dax Durax Mar 16 '13 at 22:37
  • No, a `HashMap` is a key/value storage where you can look up a value by it's key. Internally, the key/value pairs are stored in different lists, according to the hashcode of the key. – jlordo Mar 16 '13 at 22:39
0

If I am getting you right, you want the functionality of a HashSet being accomplished by a HashMap. Have a look on the HashSet documentation, probably that is what you are searching for.

HashMaps work different, to give you a hint: you can store the same string (with equal hashCode) with different keys:

String myString = "hallo";
HashMap<String,String> map = new HashMap<String,String>();
map.put("key1", myString);
map.put("key2", myString);
linqu
  • 11,320
  • 8
  • 55
  • 67
0

A hashCode by itself is not enough to look up a value: different keys can have the same hashCode. The point of having a hashCode is only to quickly narrow down the places where the hash table would have the entry for that key and that value.

Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413