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

Collision resolution in HashMap

When we put key-value pair in HashMap this could happen the hashcode of two keys could be same then how in this condition storing and retrieval of key-value will be handled. Update What I understand so far is that if two object key has same hash…
Sandeep Kumar
  • 13,799
  • 21
  • 74
  • 110
5
votes
4 answers

Iterating over member variables in Java

I have several situations where a class consists of an arbitrary (but fixed) number of variables of differing types and wish to iterate over those variables as well as use their names in code. Is there a smarter way to do this than to retype each…
mikebabcock
  • 791
  • 1
  • 7
  • 20
5
votes
5 answers

In a hashmap/unordered_map, is it possible to avoid data duplication when the value already contains the key

Given the following code: struct Item { std::string name; int someInt; string someString; Item(const std::string& aName):name(aName){} }; std::unordered_map items; Item* item = new…
Alexander Vassilev
  • 1,399
  • 13
  • 23
5
votes
6 answers

HashMap with uniqueness check

I have a class with several key-value lists. Each key (within a list) should be unique, so I use HashMap. When somewhere in the code I add a new item to a list, I am using HashMap's put(K, V). I'd like my code to throw an exception if an attempt is…
texnic
  • 3,959
  • 4
  • 42
  • 75
5
votes
5 answers

Hashing Keys in Java

In java, when I use a String as a key for Hashmap I get a little different result than when I use the string hashcode as a key in the HashMap. Any insight?
user1785771
  • 487
  • 2
  • 7
  • 18
5
votes
6 answers

Using HashMap to count instances

I have the following code to count the instances of different strings in an array; String words[] = {"the","cat","in","the","hat"}; HashMap wordCounts = new HashMap(50,10); for(String w : words) { Integer i =…
lynks
  • 5,599
  • 6
  • 23
  • 42
5
votes
3 answers

Growing a Hashmap of vectors in Matlab

I have a need for hashmap-like functionality in Matlab, where the hashmap maps vectors to other vectors, and the number of vectors (ranging in the hundreds of thousands) is not known beforehand. I tried Matlab's inbuilt Containers.Map, but that…
Matt
  • 282
  • 3
  • 13
5
votes
3 answers

How to Store unique objects to avoid the duplicates in java Set?

How to Store unique objects to avoid the duplicates in java Set? For example Consider Employee object which (Employee Id, name, salary....) list of employee of objects need to add in the Set. We need to restrict the Set for the duplicate elements…
iamjustcoder
  • 4,714
  • 10
  • 33
  • 46
5
votes
3 answers

Declare and Put String array in HashMap in one step

I am trying to insert static data into a HashMap in Java like this: HashMap instruments = new HashMap(); instruments.put("EURUSD", {"4001","EURUSD","10000","0.00001","0.1","USD"}); But the compiler doesn't like…
jule64
  • 487
  • 1
  • 6
  • 19
5
votes
12 answers

java.lang.ClassCastException: java.util.HashMap cannot be cast to java.lang.Comparable

I was trying to sort my ArrayList. java.util.ArrayList arList= new java.util.ArrayList(); arList=getList(); java.util.Collections.sort(arList); where my getList() function here public ArrayList getList() throws Exception { ArrayList…
Nidheesh
  • 4,390
  • 29
  • 87
  • 150
5
votes
3 answers

How does HashMap make sure the index calculated using hashcode of key is within the available range?

I went through source code of HashMap and have a few questions. The PUT method takes the Key and Value and does the hashing function of the hashcode of the key. calculate bucket location for this pair using the hash obtained from the previous…
Akh
  • 5,961
  • 14
  • 53
  • 82
5
votes
1 answer

Why is my HashMap allowing duplicate keys?

Hey I'm using a HashMap to keep track of services and service-requests on a BulletinBoard. However, I must have the hashcode and equals wrong because I'm getting duplicate keys. Can anyone tell why this might be? The content of the keySet:…
rtheunissen
  • 7,347
  • 5
  • 34
  • 65
5
votes
5 answers

Converting string arrays into Map

I have two string arrays keys and values String[] keys = {a,b,c,d}; String[] values = {1,2,3,4}; What is the fastest way to convert them into a map? I know we can iterate through them. But, is there any utility present?
user2434
  • 6,339
  • 18
  • 63
  • 87
5
votes
4 answers

HashMap: containsKey() Not true when it should be?

I am currently throwing an obfuscation program for school homework together. I am trying to make the program read a file and then create a new file that replaces each letter in the file with some a corresponding value that I pull from a HashMap. I…
BitPuffin
  • 51
  • 1
  • 5
5
votes
2 answers

Differences between .Net Hashtable, Java Hashtable & HashMap

Am I correct in saying that a .Net Hashtable is not synchronized while a Java Hashtable is? And at the same time a Java HashMap is not synchronized and has better performance? I am rewriting a Java app that makes heavy use of HashMaps in C# and I…
CountCet
  • 4,545
  • 7
  • 30
  • 39