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
58
votes
5 answers

HashMap implementation in Java. How does the bucket index calculation work?

I am looking at the implementation of HashMap in Java and am stuck at one point. How is the indexFor function calculated? static int indexFor(int h, int length) { return h & (length-1); } Thanks
gnreddy
  • 2,393
  • 4
  • 22
  • 18
57
votes
13 answers

Java HashMap: How to get a key and value by index?

I am trying to use a HashMap to map a unique string to a string ArrayList like this: HashMap> Basically, I want to be able to access the keys by number, not by using the key's name. And I want to be able to access said…
Derek
  • 833
  • 2
  • 9
  • 13
56
votes
8 answers

How to generate a unique hash code for string input in android...?

I wanted to generate a unique hash code for a string in put in android. Is there any predefined library is there or we have to generate manually. Please any body if knows please present a link or a code stuff.
Shashikant
  • 571
  • 1
  • 4
  • 4
56
votes
14 answers

Which data structure would you use: TreeMap or HashMap? (Java)

Description | A Java program to read a text file and print each of the unique words in alphabetical order together with the number of times the word occurs in the text. The program should declare a variable of type Map to store the…
JohnZaj
  • 3,080
  • 5
  • 37
  • 51
56
votes
9 answers

Retrieve all values from HashMap keys in an ArrayList Java

Good day, this is kind of confusing me now(brain freeze!) and seem to be missing something. Have an ArrayList which i populate with a HashMap. now i put in my HashMap and arraylist. Map.put(DATE, value1); Map.put(VALUE, value2); …
irobotxx
  • 5,963
  • 11
  • 62
  • 91
55
votes
4 answers

How to combine one hash with another hash in ruby

I have two hashes... a = {:a => 5} b = {:b => 10} I want... c = {:a => 5,:b => 10} How do I create hash c?
thefonso
  • 3,220
  • 6
  • 37
  • 54
55
votes
6 answers

How does ConcurrentHashMap work internally?

I was reading the official Oracle documentation about Concurrency in Java and I was wondering what could be the difference between a Collection returned by public static Collection synchronizedCollection(Collection c); and using for…
Adam Arold
  • 29,285
  • 22
  • 112
  • 207
53
votes
3 answers

Using an instance of an object as a key in hashmap, and then access it with exactly new object?

I have a hasmap with a key object, HashMap test; and make new Key("the same") as key.. so its like..: test.put(new Key("the same"), someObject); (without storing that key in a variable) so.. after a while... i want to access the…
Keenan Gebze
  • 1,366
  • 1
  • 20
  • 26
53
votes
6 answers

Difference between Hashtable and Collections.synchronizedMap(HashMap)

As far as I know, java.util.Hashtable synchronizes each and every method in the java.util.Map interface, while Collections.synchronizedMap(hash_map) returns a wrapper object containing synchronized methods delegating calls to the actual hash_map…
Vinoth Kumar C M
  • 10,378
  • 28
  • 89
  • 130
53
votes
5 answers

I would like to see a hash_map example in C++

I don't know how to use the hash function in C++, but I know that we can use hash_map. Does g++ support that by simply including #include ? What is a simple example using hash_map?
skydoor
  • 25,218
  • 52
  • 147
  • 201
52
votes
14 answers

Is there a way to get the value of a HashMap randomly in Java?

Is there a way to get the value of a HashMap randomly in Java?
Varuna
  • 1,343
  • 3
  • 15
  • 30
52
votes
5 answers

What exactly is bucket in hashmap?

Recently, in an interview I was asked, what exactly is a bucket in hashmap? Whether it is an array or a arraylist or what? I got confused. I know hashmaps are backed by arrays. So can I say that bucket is an array with a capacity of 16 in the start…
dgupta3091
  • 1,067
  • 1
  • 7
  • 18
52
votes
5 answers

Difference between replace and put for HashMap

I want to make a histogram by using a HashMap, the key should be the delay, the value the amount of times this delay occurs. I am doubting to use the HashMap replace or the HashMap put function if an already existing delay has an new occurence. I…
StudentX
  • 565
  • 1
  • 4
  • 7
52
votes
3 answers

Get value from hashmap based on key to JSTL

I want to get the value of HashMap based on key. HashMap> map = new HashMap>(); ArrayList arrayList = new ArrayList(); map.put("key", arrayList); request.setAttribute("key",…
newbie
  • 1,884
  • 7
  • 34
  • 55
51
votes
8 answers

Is there a Java equivalent of Python's defaultdict?

In Python, the defaultdict class provides a convenient way to create a mapping from key -> [list of values], in the following example, from collections import defaultdict d = defaultdict(list) d[1].append(2) d[1].append(3) # d is now {1: [2, 3]} Is…
gatoatigrado
  • 16,580
  • 18
  • 81
  • 143