r/learnjava • • Jan 25 '21

Can someone explain what is this hashmap and how to use it? With sime examle for dummies.

Thank you!

1 Upvotes

5 comments sorted by

5

u/[deleted] Jan 25 '21

It’s a data structure. It works by key and value like a pair. Each key is unique and works well went trying to control data so that you can easily pull from data on the values given keys. It’s really reliable to use in many cases.

1

u/AquaChad Jan 25 '21

You could probably google this and find equally good examples. Ultimately it’s a dictionary, mapping a key to a value. A common example is a phone book. Unlike an array, you want to access the data using some key, which could be anything, as opposed to some specific index. You don’t want to have to know exactly what page and like “John Doe” exists in the phone book. You just want to find “John Doe” (assuming only one John Doe for simplicity) With the map, you provide the key and value when building it and when referencing it you need only provide the key (person’s name) and you would get the phone number back. These key/value pairs can be be mixed, so you could have keys that are Strings, ints, classes you created, etc. and the same for the values. So for a phone book that would be <String, Integer> (assuming a phone number with no dashes). Again, probably worth looking up the actual details involved like hashing and the concept of the buckets.

1

u/AreTheseMyFeet Jan 25 '21

Minor, not-important-in-this-context advice:
Never use numeric types for phone numbers. Integer, Long etc etc will mangle many valid numbers (which can contain non numeric characters) and can make handling and persisting the data an absolute pain.
"Phone numbers" would have been better termed "phone addresses" as they are much more similar to textual addresses than they are real numbers. Do you ever need to add, subtract, multiply or divide a phone number?

https://stackoverflow.com/questions/24353778/which-is-best-data-type-for-phone-number-in-mysql-and-what-should-java-type-mapp/24353813

If you really want to keep numeric format/storage for whatever reason there is the E.164 ISO standard that you can convert your inputs in to and they won't mangle them but you'd then probably have to spent an amount of time doing custom formatting and conversion which is just easier avoided by using Strings.

1

u/AquaChad Jan 25 '21

Thanks for sharing! Not something I would’ve thought of off the bat if I encounter this in the future so much appreciated

1

u/fosizzle Jan 25 '21

It's a datatype to hold a collection of objects. Arrays can hold collections, Lists can hold collections, and Maps. (And more, of course)

Maps are very useful when you have a collection of objects, but you need to access a specific object in the collection, and not the whole collection. Maps provide quick access to a single object in the collection.

A hashmap might be a bad collection type if you want to preserve the order of something.