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

Why is the variable declared as Map and initialized as HashMap; aren't they different types?

Let's say I want to make a HashMap of grades. Map grades = new HashMap(); grades.put("John", 87); // this work due to auto-boxing right? grades.put("Luke", Integer(85)); // non-autoboxed, is this redundant? Why…
bambo222
  • 419
  • 7
  • 15
5
votes
1 answer

Using collect closure method to populate a HashMap in groovy

I am trying to populate a Map from an List. Here's what I am doing. itemNoList = [1,2,3,4] bookMap = [:] bookMap = itemNoList.collect{ [ (it) : it+1 ] } When I do this, the bookMap changes to ArrayList type and now has a List of HashMap. bookMap is…
Wizard
  • 1,154
  • 2
  • 14
  • 41
5
votes
3 answers

Java Session Implementation

I am developing a multiplayer online game. I have the following issue: When the user breaks his/her connection with the server, he needs to reconnect. At the first connection, during registration, the registration module produces a special…
Artem Moskalev
  • 5,748
  • 11
  • 36
  • 55
5
votes
3 answers

Do keys with different hashes also get mapped to the same index in HashMap?

Looking at the code specifically line 393, it looks like different hashes have been mapped to same index. I had an understanding that the hashcode is used to determine what bucket in a HashMap is to be used, and the bucket is made up of a linked…
JavaDeveloper
  • 5,320
  • 16
  • 79
  • 132
5
votes
9 answers

Using the keySet() method in HashMap

I have a method that goes through the possible states in a board and stores them in a HashMap void up(String str){ int a = str.indexOf("0"); if(a>2){ String s =…
andandandand
  • 21,946
  • 60
  • 170
  • 271
5
votes
6 answers

Why is getEntry(Object key) not exposed on HashMap?

Here is my use case, I have an object that is logically equal to my HashMap key but not the same object (not ==). I need to get the actuall key object out of the HashMap so that i can synchronise on it. I am aware that i can iterate over the ketSet,…
mR_fr0g
  • 8,462
  • 7
  • 39
  • 54
5
votes
1 answer

Why it is necessary to override hashcode and equals method of key for Hashmap?

I created a HashMap having Student as key and String as value. Now everywhere i have read It is necessary to override equals and hashcode method if using as a key for hashmap. But I did not override it. And insert multiple key value pairs in…
Raj
  • 692
  • 2
  • 9
  • 23
5
votes
3 answers

Is hashMap implemented as an array of linked lists

While reading about HashMap I see that it is implemented as an array of buckets? Now are these buckets always linked lists? If so, why are they called buckets and not linked lists?
Victor
  • 16,609
  • 71
  • 229
  • 409
5
votes
4 answers

Initial capacity for a HashSet

What Initial Capacity should I use for a HashSet into which I know that I am going to insert 1000 integers to prevent the need for any internal rebuilds ? At first I though that I should use 1000 but reading the description of the constructor that…
epeleg
  • 10,347
  • 17
  • 101
  • 151
5
votes
3 answers

Replace a big hashmap in AS

I have a hashmap which stores around 1 G of data is terms of key value pairs. This hashmap changes every 15 days. It will be loaded into memory and used from there. When a new hashmap has to be loaded into the memory, there would be several…
Abhi
  • 129
  • 6
5
votes
3 answers

ArrayList> to String[]

i have data fetched from my webservice in ArrayList> Now i want to convert each object of the above to String[] how do i do this? any help would be much appreciated!
Niraj Adhikari
  • 1,678
  • 2
  • 14
  • 28
5
votes
2 answers

Issue with declaration of Map>

Java provides me by a way of filtering the java classes that you can use to build in this case the new HashMap, for example: I can do that: Map map1 = new HashMap(); It is correct,…
Ivan
  • 53
  • 1
  • 6
5
votes
3 answers

How to put all value in arraylist to hashmap in android?

I have an ArrayList and I want to put all the array data in my hash map but the problem is all I get is the last index value of the array list. Here's my code ArrayList imagesFileName = new ArrayList(); public String[]…
NewDroidDev
  • 1,656
  • 5
  • 19
  • 33
5
votes
6 answers

Creating subset of HashMap based on some specifications?

So I have the following HashMap: HashMap> map; I want to create a new HashMap that is only composed of the k/v pairs in map that have a value (the list) whose length is less than a certain "x". The only way I know how to…
r123454321
  • 3,323
  • 11
  • 44
  • 63
5
votes
2 answers

Quickly finding if there are 2 or more equal numbers

I have an array of N different numbers that change frequently. After every change there is a chance that two or more numbers have become equal, and I don't want that. The number N can be as big as the maximum possible integer. Knowing that changes…