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
4 answers

What does <<= operator mean in Java?

Can you please explain this code snippet from HashMap constructor specifically the line capacity <<= 1: // Find a power of 2 >= initialCapacity 198 int capacity = 1; 199 while (capacity < initialCapacity) 200 capacity…
Geek
  • 26,489
  • 43
  • 149
  • 227
5
votes
2 answers

How to declare HashMap with different types?

I have a function, declared like this: public synchronized void update(HashMap data) data contains strings and ints, but the Comparable gives a warning Comparable is a raw type. References to generic type Comparable should be…
Marcus Toepper
  • 2,403
  • 4
  • 27
  • 42
5
votes
4 answers

Regarding HashMap implementation in java

I was trying to do research on hashmap and came up with the following analysis: https://stackoverflow.com/questions/11596549/how-does-javas-hashmap-work-internally/18492835#18492835 Q1 Can you guys show me a simple map where you can show the…
DON
  • 43
  • 1
  • 7
5
votes
3 answers

Using table guava for hashbasedTable

I am planning to use table guava for a 3D hash map implementation. I downloaded that and I am able to import the files. My requirement is the below I have the below file in my hand and I just have to aggregate the file accordingly and that is shown…
NandaKumar
  • 905
  • 4
  • 15
  • 19
5
votes
1 answer

Sending HashMap parameter to Web Service from PHP

Actually, the problem is NOT how to do it, but if it's a design mistake. I'm worried because I've read a lot about using only standard data types in WS. However, I had no problem implementing one that receives a HashMap, and filling that parameter…
Federico Cristina
  • 2,203
  • 1
  • 19
  • 37
5
votes
2 answers

Perl changing value within a conditional before entering the conditional?

I am working on a Perl script that is to help with the automation of scanning of machines on our network. I am not a programmer by trade, but none-the-less this project has been assigned to me, and I am quite stumped. Before I explain the nature of…
5
votes
2 answers

Unable to cast a HashMap to a Interface extending Map

This is probably a simple misunderstanding on my part. Have a simple interface: public interface IParams extends Map { } Then I try to use: IParams params = (IParams) new HashMap(); Passes syntax and compile but at…
Matt Thompson
  • 773
  • 1
  • 10
  • 26
5
votes
1 answer

fail fast behaviour of java HashMap

I played around with java.util.HashMap to learn what the fail-fast behaviour is. HashMap map = new HashMap(); map.put("jon", 10); map.put("sean", 11); map.put("jim", 12); map.put("stark", 13); map.put("vic", 14); Set keys = map.keySet(); for(Object…
damon
  • 8,127
  • 17
  • 69
  • 114
5
votes
2 answers

scala hashmap multiple values

I would like to implement a hashtable with int keys and string values. I tried the following: import scala.collection.mutable.HashMap val test_map = new HashMap[Int, String] test_map += 10 -> "prog_1" test_map += 20 -> "prog_2" test_map += 25 ->…
richsoni
  • 4,188
  • 8
  • 34
  • 47
5
votes
2 answers

Create seq of maps from two or more seqs

I'm new to Clojure and I was wondering if there's a way to create a sequence of maps from two or more sequences. Let's say you have: (def numbers '(1 2 3)) (def letters '("a" "b" "c")) (def shapes '("circle" "square" "triangle")) If you merged…
kreek
  • 8,774
  • 8
  • 44
  • 69
5
votes
4 answers

Understanding HashMap

Ok, here is the bit I do not understand. If you attempt to retrieve an object using the get() method and null is returned, it is still possible that null may be stored as the object associated with the key you supplied to the get() method. You can…
A User
  • 375
  • 2
  • 4
  • 13
5
votes
2 answers

hashmap in Application context php

I am trying to implement a hashmap (associative array in PHP) in PHP which is available application wide i.e store it in application context, it should not be lost when the program ends. How I can I achieve this in PHP? Thanks,
cldy1020
  • 711
  • 2
  • 9
  • 15
5
votes
2 answers

Reading from Properties file v/s HashMap lookup

Which is a more efficient way of accessing (key,value) pairs in terms of both memory and computation: reading from a properties file using properties.getProperty("key") or loading the entire properties file into a HashMap in the beginning of the…
Andy
  • 1,080
  • 5
  • 20
  • 35
5
votes
4 answers

Both hashed and indexed list or array?

Is there any class in Java, which holds an array of elements both in order and optimized for fast searching? I.e. I need to retrieve elements both by numeric index (like in Vector) and by hash (like in HashMap). LinkedHashMap does not match I think…
Suzan Cioc
  • 29,281
  • 63
  • 213
  • 385
5
votes
4 answers

Why does ExecutorService deadlock when performing HashMap operations?

When running the following class the ExecutionService will often deadlock. import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.Callable; import…
Stephen
  • 19,488
  • 10
  • 62
  • 83