Questions tagged [hashmap]

A data structure that uses a hash function to map identifying values, known as keys, to their associated values

A hash map (or hash table) is a data structure which contains "key-value" pairs and allows retrieving values by key.

The most attractive feature is fast lookup of elements, particularly for large numbers of elements. Hash maps work by using a hash function to transform keys into a hash number that is then used as an index into an array of "buckets" containing one or more elements. This allows constant time access to the relevant bucket, followed by a linear search for the desired element within the bucket. When the number of elements in each bucket is kept low (possibly by dynamically resizing the array of buckets as elements are inserted) this offers constant time lookup on average even when the number of elements in the hash map increases. This can be a significant advantage compared to lookup in a tree-based structures which needs to perform more steps as the number of elements increases.

A drawback of hash tables is that elements are not stored in an obvious or meaningful order, as a good hash function will not map neighbouring keys to neighbouring buckets.

If many mappings are to be stored in a HashMap instance, creating it with a sufficiently large capacity will allow the mappings to be stored more efficiently than letting it perform automatic rehashing as needed to grow the table.

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.) This is typically accomplished by synchronizing on some object that naturally encapsulates the map. If no such object exists, the map should be "wrapped" using the Collections.synchronizedMap method. This is best done at creation time, to prevent accidental unsynchronized access to the map:

Map m = Collections.synchronizedMap(new HashMap(...));

The iterators returned by all of this class's "collection view methods" are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.

This class is a member of the Java Collections Framework.

Official docs: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html

Stackoverflow Link: Differences between HashMap and Hashtable?

15203 questions
4
votes
6 answers

Using char[] array in HashMap in java

I am using a HashMap with a char array as the key. But when I put the key, value into the HashMap and print it the value printed as the key is some strange value. If I use a string instead, it is working fine. Please let me know how to make this…
vamsi360
  • 55
  • 1
  • 1
  • 5
4
votes
4 answers

Can I use HashMap of characters in place of String?

I want to have a function to build a String from inputted characters and stop building if it gets an input character that it contains. I know I can use String.contains() for this but I am learning about HashMaps and am wondering if a faster way to…
David Tejuosho
  • 177
  • 1
  • 14
4
votes
1 answer

Android - Save Map to file

How can I save this kind of map to file? (it should work for an android device too) I tried: Properties properties = new Properties(); for (Map.Entry entry : map.entrySet()) { …
Ziv Sion
  • 424
  • 4
  • 14
4
votes
1 answer

How to get memory occupied by an object in rust from the code itself

I have a requirement to read the memory occupied by an object based on some events. Is there's a simple method that I can use from the standard library ? I need to access the memory usage of the following object which contains nested…
Lahiru Udayanga
  • 309
  • 4
  • 13
4
votes
1 answer

Prefer to insert node into the head or tail of the linked list when we implement a separate chaining HashMap?

PS: Because many people in SO don't like discussing the motivation/trade-off of JDK implementation details, they think JDK engineers have a right to do it without telling anybody. (a previous post about JDK motivation has been closed), this question…
maplemaple
  • 1,297
  • 6
  • 24
4
votes
6 answers

C: Storing up to a million entries in a hash table

I'm working on a project where efficiency is crucial. A hash table would be very helpful since I need to easily look up the memory address of a node based on a key. The only problem I foresee is this hash table will need to handle up to 1 million…
Ian Burris
  • 6,325
  • 21
  • 59
  • 80
4
votes
1 answer

Why does entry need the ownership of key?

The declaration of entry is pub fn entry(&mut self, key: K) -> Entry<'_, K, V> // key is move into entry whereas the one for get is pub fn get(&self, k: &Q) -> Option<&V> where // k is just a shared reference K: Borrow, Q:…
nalzok
  • 14,965
  • 21
  • 72
  • 139
4
votes
1 answer

Why does the Java HashMap implementation use transfer() instead of put() when resizing?

In the Java 7 HashMap implementation, in the resize method, it calls transfer which moves old elements to a new table. Why have they written a new method instead of calling put with all the old elements? The resize won't be triggered again due to…
Runpeng Chen
  • 105
  • 8
4
votes
5 answers

Check if all values of a map are true

I have one Map map = new HashMap<>();. Consider there are five keys in it. map.put("A", true); map.put("B", true); map.put("C", false); map.put("D", true); map.put("E", true); I need to set one boolean flag as true if all the…
Anam Qureshi
  • 161
  • 2
  • 8
4
votes
5 answers

Performance for HashMap when Key is Guaranteed Unique

If the keys I wish to use are guaranteed to be unique (or at least the assumption can be made that the keys are unique), does using a 'vanilla' ConcurrentHashMap provide the best performance, or does a hashing function or put method need to be…
D. Moore
  • 124
  • 1
  • 7
4
votes
3 answers

Java HashMap with ArrayList wildcards

I have a HashMap where the values are ArrayLists, and I'm trying to write a function to accept generic instances of these HashMaps HashMap> myMap = new HashMap>(); public static void…
Kevin
  • 41
  • 1
  • 2
4
votes
4 answers

Using Map as a @RequestBody in Spring Boot Rest API is not working

I want retrieve a custom json object from client for which I am reading post body using a map. But when I try to hit the API I am getting java.lang.NoSuchMethodException: java.util.Map.(). I am pretty sure it should work as I have written…
Pradyskumar
  • 296
  • 1
  • 3
  • 15
4
votes
3 answers

HashMap data structure, but values are added instead of replaced

I am seaching for a data structure that is almost exactly a HashMap, but the problem with HashMaps is that most of the data stored in key value pairs is lost by calling the putAll() method on two HashMaps, due to the replacement…
doej1367
  • 311
  • 2
  • 12
4
votes
3 answers

How to create a custom iterator for a Map implementation?

I implemented a unique map. It's a hashmap which is bi-directional, where not only keys are unique but values too. public interface UniqueMap{ V uniquePut(K key, V value); UniqueMap inverse(); } This is a possible…
DarkLeafyGreen
  • 69,338
  • 131
  • 383
  • 601
4
votes
1 answer

Using Box<> with HashMap<> in Rust

I need to create a large HashMap in Rust, which is why I thought of using the Box to use the heap memory. My question is about what is the best way to keep this data, certainly I only thought of two possible ways (anticipating that I am not so…
Giuseppe
  • 531
  • 1
  • 5
  • 19