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
63
votes
9 answers

Efficient way to Handle ResultSet in Java

I'm using a ResultSet in Java, and am not sure how to properly close it. I'm considering using the ResultSet to construct a HashMap and then closing the ResultSet after that. Is this HashMap technique efficient, or are there more efficient ways of…
Deepak
  • 6,684
  • 18
  • 69
  • 121
63
votes
2 answers

Is it a good idea to store data as keys in HashMap with empty/null values?

I had originally written an ArrayList and stored unique values (usernames, i.e. Strings) in it. I later needed to use the ArrayList to search if a user existed in it. That's O(n) for the search. My tech lead wanted me to change that to a HashMap and…
dozer
  • 861
  • 1
  • 11
  • 22
63
votes
5 answers

HashMap vs Switch statement performance

A HashMap essentially has O(1) performance while a switch state can have either O(1) or O(log(n)) depending on if the compiler uses a tableswitch or lookup switch. Understandably, if a switch statement is written as such, switch (int) { case 1: …
Joe C
  • 1,788
  • 2
  • 17
  • 27
63
votes
5 answers

What is a hash map in programming and where can it be used

I have often heard people talking about hashing and hash maps and hash tables. I wanted to know what they are and where you can best use them for.
Saif Bechan
  • 16,551
  • 23
  • 83
  • 125
63
votes
9 answers

Correct way to initialize HashMap and can HashMap hold different value types?

So I have two questions about HashMaps in Java: What is the correct way to initialize a HashMap? I think it might be best in my situation to use: HashMap x = new HashMap(); But Eclipse keeps suggesting that I use: HashMap map…
Tony Stark
  • 24,588
  • 41
  • 96
  • 113
62
votes
3 answers

Printing a java map Map - How?

How to I print information from a map that has the object as the value? I have created the following map: Map objectSet = new HashMap<>(); The object has its own class with its own instance variables I have already populated the…
Gandolf
  • 637
  • 1
  • 5
  • 6
62
votes
7 answers

How does Java order items in a HashMap or a HashTable?

I was wondering how Java orders items in the Map (HashMap or Hashtable) when they are added. Are the keys ordered by the hashcode, memory reference or by allocation precedence...? It's because I've noticed same pairs in the Map are not always in the…
Eyad Salah
  • 1,084
  • 1
  • 11
  • 22
61
votes
3 answers

Performant Haskell hashed structure.

I am writing program that does alot of table lookups. As such, I was perusing the Haskell documentation when I stumbled upon Data.Map (of course), but also Data.HashMap and Data.Hashtable. I am no expert on hashing algorithms and after inspecting…
providence
  • 29,135
  • 13
  • 46
  • 62
61
votes
4 answers

What is the smartest way to copy a Map in Kotlin?

I'd like to get a new instance of some Map with the same content but Map doesn't have a built-in copy method. I can do something like this: val newInst = someMap.map { it.toPair() }.toMap() But it looks rather ugly. Is there any more smarter way to…
N. Kudryavtsev
  • 3,556
  • 1
  • 26
  • 30
61
votes
2 answers

Iterate over elements of List and Map using JSTL tag

If I have a JSF backing bean return an object of type ArrayList, I should be able to use to iterate over the elements in the list. Each element contains a map and although the question of how to access the map content through JSTL has…
volvox
  • 3,014
  • 16
  • 51
  • 80
61
votes
9 answers

Understanding the workings of equals and hashCode in a HashMap

I have this test code: import java.util.*; class MapEQ { public static void main(String[] args) { Map m = new HashMap(); ToDos t1 = new ToDos("Monday"); ToDos t2 = new ToDos("Monday"); ToDos t3 = new…
andandandand
  • 21,946
  • 60
  • 170
  • 271
61
votes
4 answers

Why hashmap lookup is O(1) i.e. constant time?

If we look from Java perspective then we can say that hashmap lookup takes constant time. But what about internal implementation? It still would have to search through particular bucket (for which key's hashcode matched) for different matching…
genonymous
  • 1,598
  • 3
  • 18
  • 27
60
votes
6 answers

How to do an array of hashmaps?

This is what I tried to do, but it gives me a warning: HashMap[] responseArray = new HashMap[games.size()]; Type safety: The expression of type HashMap[ ] needs unchecked conversion to conform to HashMap[ ]
Joren
  • 9,623
  • 19
  • 63
  • 104
59
votes
8 answers

Map.Entry: How to use it?

I'm working on creating a calculator. I put my buttons in a HashMap collection and when I want to add them to my class, which extends JPanel, I don't know how can I get the buttons from my collection. So I found on the internet the 2 last lines of…
user1079425
58
votes
4 answers

How do I collect the values of a HashMap into a vector?

I can not find a way to collect the values of a HashMap into a Vec in the documentation. I have score_table: HashMap and I want to get all the Scores into all_scores: Vec. I was tempted to use the values method (all_scores =…
Hugo Trentesaux
  • 1,584
  • 1
  • 16
  • 30