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

hash that maps strings to integers

Looking for some hash function to make string to int mapping with following restrictions. restrictions: Same strings go to same number. Different strings go to different numbers. During one run of…
Night Walker
  • 20,638
  • 52
  • 151
  • 228
4
votes
2 answers

How to store a value in HashMap (Android)?

im worked in soap message, using SAXparser to retrieve the value(from Webservice) stored in ArrayList and the ArrayList working fine, but i want to store in HashMap, because Using key to identify a each name has certain SystemId, Please any one help…
Sampath Kumar
  • 1,650
  • 4
  • 14
  • 16
4
votes
4 answers

Constructor in a class of static methods

I've got a class of static methods that can be performed on a map held within the class, and I want the map to be set up when the class is called. I've tried using a private contructor, but it isn't being called. The relevant parts of my code…
DenverCoder8
  • 401
  • 7
  • 15
4
votes
4 answers

Hash Map Object Key

I'm using this class as my key to Hashmap with overriden hasCode() and equals() public class Design { private double[] factors = null; public double[] getFactors() { return factors; } public void setFactors(double[] factors) { this.factors…
JR Galia
  • 17,229
  • 19
  • 92
  • 144
4
votes
5 answers

How bad is to use Hashmaps and ArrayLists while using huge data?

I am reading XML document into HashMaps, ArrayLists so that the relationship maintains even in the memory. My code does my job but i am worried about the iterations or function calls i am performing on this huge maps and lists. Currently the xml…
user1061293
  • 167
  • 1
  • 4
  • 14
4
votes
1 answer

Cloning a java LinkedHashMap

What is the best of cloning a LinkedHasMap in Java? I already tried: Map clonedMap = new LinkedHashMap(originalMap); But that didn't work.
RedEagle
  • 4,418
  • 9
  • 41
  • 64
4
votes
8 answers

Can you explain Perl's hash system to a PHP guy?

How do Perl hashes work? Are they like arrays in PHP or some completely different beast? From what I understand all it is is an associative array right? This is what I thought until I began to talk to a Perl programmer who told me I was completely…
ehime
  • 8,025
  • 14
  • 51
  • 110
4
votes
5 answers

Java HashMap: adding to arraylist

I'm using the HashMap class and it looks like this: HashMap> fileRank = new HashMap>(); I'm wondering how to add a new String into the Arraylist after the initial put. fileRank.put(word,…
DomX23
  • 867
  • 5
  • 13
  • 26
4
votes
4 answers

Run time to insert n elements into an empty hash table

People say it takes amortized O(1) to put into a hash table. Therefore, putting n elements must be O(n). That's not true for large n, however, since as an answerer said, "All you need to satisfy expected amortized O(1) is to expand the table and…
Claudiu
  • 224,032
  • 165
  • 485
  • 680
4
votes
4 answers

How to call function from hashmap in Scala

I'm pretty new to scala and basically I want to have a couple of functions coupled to a string in a hashmap. However I get an error at subscribers.get(e.key)(e.EventArgs); stating Option[EventArgs => Unit] does not take parameters... Example…
Seba Kerckhof
  • 1,294
  • 1
  • 14
  • 23
4
votes
6 answers

Get variable type in a HashMap in java

I have a HashMap and stored some data from 3 different types (Integer,String,Long). How Can I find out what is the type of a value with a specific key?
Ariyan
  • 14,760
  • 31
  • 112
  • 175
4
votes
5 answers

Tokenize big files to hashtable in Java

I'm having this problem: I'm reading 900 files and, after processing the files, my final output will be an HashMap>. First string is fileName, second string is word and the double is word frequency. The processing…
recoInrelax
  • 697
  • 2
  • 16
  • 33
4
votes
8 answers

Java HashMap indexed on 2 keys

I want to create a HashMap in java for users with preferences. This would be easy to do in a database, but unfortunately I can't use a database. What I need is a way to find a user by name in the HashMap, and to find all the users with a certain…
Marius
  • 57,995
  • 32
  • 132
  • 151
4
votes
2 answers

Using HashMap as Collection in Java

JAXB doesn't let you unmarshal already existing xml structures into HashMaps if they are not exactly the way JAXB expects them. JAXB is fine with handling e.g. LinkedLists and filling them. I was thinking of creating a interface with a getKey()…
Franz Kafka
  • 10,623
  • 20
  • 93
  • 149
4
votes
2 answers

Java: Compact a HashMap (analogue of ArrayList#trimToSize)

Is there a way to compact a HashMap in the sense that you can with an ArrayList through its trimToSize() method? One way I can think of is to iterate through all of the entries in the present map and populate a new one, then replace the original…
bguiz
  • 27,371
  • 47
  • 154
  • 243