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

Sorting by values in HashMap class using Java

I'm trying to get results HashMap sorted by value. This is HashMap's keys and values: map.put("ertu", 5); map.put("burak", 4); map.put("selin", 2); map.put("can", 1); I try to get results like this: 1 = can 2 = selin 4 = burak 5 = ertu Here is my…
Ertuğrul Çetin
  • 5,131
  • 5
  • 37
  • 76
5
votes
1 answer

Hashmap stuck on get

I have a strange issue with HashMap. There are multiple threads that accessing same hashmap (not threadsafe). Sometime, the process gets stuck. when I inspect the thread stack, i see many threads in state: java.lang.Thread.State: RUNNABLE at…
user2479100
  • 105
  • 1
  • 2
  • 7
5
votes
2 answers

Java.lang.NullPointerException in doInBackground put HashMap in ArrayList

I have developed app which connects to server and receive JSON response .Till this it works fine.But then it puts in Hashmap and HashMap in ArrayList to display data.It gives error on while putting Hashmap in ArrayList.My LogCat is 06-03…
Passion
  • 662
  • 1
  • 11
  • 29
5
votes
4 answers

hashmap for 2d(3d) coordinates (i.e. vector of doubles)?

I wonder if there is a general all-around solution for a hash map for coordinates (in 2d or 3d, i.e. a vector of doubles)? An example here demonstrates how to create a custom hash-map for pair, but it does not seem to be trivial to come-up…
Denis
  • 1,526
  • 6
  • 24
  • 40
5
votes
3 answers

Clojure: How do I apply a function to a subset of the entries in a hash-map?

I am not to Clojure and attempting to figure out how to do this. I want to create a new hash-map that for a subset of the keys in the hash-map applies a function to the elements. What is the best way to do this? (let [my-map {:hello "World" :try…
Jeroen Dirks
  • 7,705
  • 12
  • 50
  • 70
5
votes
2 answers

hash table for strings in c++

i've done in the past a small exercise about hashtable but the user was giving array size and also the struct was like this (so the user was giving a number and a word each time as input) struct data { int key; char c[20]; }; So it was quite…
captain monk
  • 719
  • 4
  • 11
  • 34
5
votes
1 answer

How to print all words stored in a Tree , wherin trie has been implemented using Hashmap in Java?

I want to print or retrieve all the words stored in Trie Data Structure. This is because I want to compute Edit distance between a misspelled word and a word in Dictionary. Therefore I was thinking of retrieving each word from Trie and compute Edit…
user2281107
  • 319
  • 2
  • 5
  • 14
5
votes
1 answer

Suppressing Warnings when using a dynamic class reference

Background An existing system creates a plethora of HashMap instances via its Generics class: import java.util.Map; import java.util.HashMap; public class Generics { public static Map newMap() { return new HashMap(); } …
Dave Jarvis
  • 30,436
  • 41
  • 178
  • 315
5
votes
5 answers

Inputting Arrays into a Hashmap

I feel like this is a very simple question, but I couldn't find an answer. Can you input an array object to the put method of a HashMap? Example: Say you have a HashMap: HashMap map = new HashMap (); You have an…
Matt
  • 1,792
  • 5
  • 21
  • 33
5
votes
2 answers

Using pair as key for hash_map under Visual Studio

Try to use pair as key value for hash_map under Visual Studio 2010. Could not compile it. int _tmain(int argc, _TCHAR* argv[]) { hash_map , int> months; months[pair(2,3)] = 1; int d; cin >> d; return…
user2030574
  • 107
  • 2
  • 5
5
votes
3 answers

Spring bean map with dynamic keys and values

Right now i've application related data in spring bean map and passed this map to other classes as ref. Map is defined as below
Javee
  • 71
  • 1
  • 1
  • 8
5
votes
4 answers

Questions about implementing my own HashMap in Java

I am working on an assignment where I have to implement my own HashMap. In the assignment text it is being described as an Array of Lists, and whenever you want to add an element the place it ends up in the Array is determined by its hashCode. In my…
Per John
  • 63
  • 1
  • 1
  • 4
5
votes
2 answers

Implementing a Hashmap in C++ :: hashing function for templated data type

I've been using STL's unordered_map recently and while it seems to work nicely I don't quite understand how the hashing function works given that the data type is given as a template parameter. In an effort to understand this data structure more…
CCJ
  • 1,619
  • 26
  • 41
5
votes
2 answers

Why isn't this Ruby hash what I thought it would be?

I have this code: $ze = Hash.new( Hash.new(2) ) $ze['test'] = {0=> 'a', 1=>'b', 3 => 'c'} $ze[5][0] = 'one' $ze[5][1] = "two" puts $ze puts $ze[5] And this is the output: {"test"=>{0=>"a", 1=>"b", 3=>"c"}} {0=>"one", 1=>"two"} Why isn't the…
Turnsole
  • 3,422
  • 5
  • 30
  • 52
5
votes
1 answer

Java WeakHashMap with multiple keys?

I'm looking for an equivalent to the WeakHashMap class, except that it maps multiple keys to a value, so it's really more like WeakHashMap WeakHashMap etc. The way you get and set entries would be like a…
Li Haoyi
  • 15,330
  • 17
  • 80
  • 137