14.12.2020

Hashcode Generate Key For Hashmap

11

I have a 2D array of Integers. I want them to be put into a HashMap. But I want to access the elements from the HashMap based on Array Index. Something like:

Hashmap Implementation Java

For A[2][5], map.get(2,5) which returns a value associated with that key. But how do I create a hashMap with a pair of keys? Or in general, multiple keys: Map<((key1, key2,.,keyN), Value) in a way that I can access the element with using get(key1,key2,…keyN).

EDIT : 3 years after posting the question, I want to add a bit more to it

Nov 04, 2014  In this tutorial, we will see the importance of hashCode and equals method while writing code by using HashMap. We will see first what the default behaviour of these methods and later will see how to override these methods. Both hashCode and equals method are defined in Java.lang.Object class. HashCode: public. If the hashcode method is not overridden, the answer to this question really depends on if the same key object which was used to 'put' is going to used for 'get' as well: a) If the same key object is used - 'get' will find the value. Because it will locate the bucket using the same 'key' and hence will find the value object. Jul 03, 2017  You don't override the hash code and equals method in the Hash Map but you would have to do so in the type/class of your hash map key. If you have a HashMap then you would have to override hash code and equals in the Car class.

I came across another way for NxN matrix.

Array indices, i and j can be represented as a single key the following way:

And the indices can be retrevied from the key in this way:

Answers:

There are several options:

Map of maps

Wrapper key object

Implementing equals() and hashCode() is crucial here. Then you simply use:

and:

Table from Guava

Table uses map of maps underneath.

Notice that special Key class is the only approach that scales to n-dimensions. You might also consider:

but that’s terrible from performance perspective, as well as readability and correctness (no easy way to enforce list size).

Maybe take a look at Scala where you have tuples and case classes (replacing whole Key class with one-liner).

Answers:

When you create your own key pair object, you should face a few thing.

First, you should be aware of implementing hashCode() and equals(). You will need to do this.

Second, when implementing hashCode(), make sure you understand how it works. The given user example

is actually one of the worst implementations you can do. The reason is simple: you have a lot of equal hashes! And the hashCode() should return int values that tend to be rare, unique at it’s best. Use something like this:

This is fast and returns unique hashes for keys between -2^16 and 2^16-1 (-65536 to 65535). This fits in almost any case. Very rarely you are out of this bounds.

Third, when implementing equals() also know what it is used for and be aware of how you create your keys, since they are objects. Often you do unnecessary if statements cause you will always have the same result.

If you create keys like this: map.put(new Key(x,y),V); you will never compare the references of your keys. Cause everytime you want to acces the map, you will do something like map.get(new Key(x,y));. Therefore your equals() does not need a statement like if (this obj). It will never occure.

Instead of if (getClass() != obj.getClass()) in your equals() better use if (!(obj instanceof this)). It will be valid even for subclasses.

So the only thing you need to compare is actually X and Y. So the best equals() implementation in this case would be:

So in the end your key class is like this:

You can give your dimension indices X and Y a public access level, due to the fact they are final and do not contain sensitive information. I’m not a 100% sure whether private access level works correctly in any case when casting the Object to a Key.

If you wonder about the finals, I declare anything as final which value is set on instancing and never changes – and therefore is an object constant.

Answers:

You can’t have an hash map with multiple keys, but you can have an object that takes multiple parameters as the key.

Create an object called Index that takes an x and y value.

Then have your HashMap<Index, Value> to get your result. 🙂

Answers:

Two possibilities. Either use a combined key:

Or a Map of Map:

Answers:

Implemented in common-collections [MultiKeyMap] (https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/map/MultiKeyMap.html)

Answers:

Create a value class that will represent your compound key, such as:

taking care to override equals() and hashCode() correctly. If that seems like a lot of work, you might consider some ready made generic containers, such as Pair provided by apache commons among others.

Hashcode Generate Key For Hashmap In C

There are also many similar questions here, with other ideas, such as using Guava’s Table, although allows the keys to have different types, which might be overkill (in memory use and complexity) in your case since I understand your keys are both integers.

Answers:

If they are two integers you can try a quick and dirty trick: Map<String, ?> using the key as i+'#'+j.

If the key i+'#'+j is the same as j+'#'+i try min(i,j)+'#'+max(i,j).

Answers:

You could create your key object something like this:

public class MapKey {

}

The advantage of this is: It will always make sure you are covering all the scenario’s of Equals as well.

NOTE: Your key1 and key2 should be immutable. Only then will you be able to construct a stable key Object.

Answers:

we can create a class to pass more than one key or value and the object of this class can be used as a parameter in map.

Answers:

Use a Pair as keys for the HashMap. JDK has no Pair, but you can either use a 3rd party libraray such as http://commons.apache.org/lang or write a Pair taype of your own.

Answers:

You can also use guava Table implementation for this.

Table represents a special map where two keys can be specified in combined fashion to refer to a single value. It is similar to creating a map of maps.

Tags: hash

This class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value.

To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method.

An instance of Hashtable has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. Note that the hash table is open: in the case of a 'hash collision', a single bucket stores multiple entries, which must be searched sequentially. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. The initial capacity and load factor parameters are merely hints to the implementation. The exact details as to when and whether the rehash method is invoked are implementation-dependent.

Generally, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the time cost to look up an entry (which is reflected in most Hashtable operations, including get and put).

The initial capacity controls a tradeoff between wasted space and the need for rehash operations, which are time-consuming. No rehash operations will ever occur if the initial capacity is greater than the maximum number of entries the Hashtable will contain divided by its load factor. However, setting the initial capacity too high can waste space.

If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table.

This example creates a hashtable of numbers. It uses the names of the numbers as keys:

To retrieve a number, use the following code:

The iterators returned by the iterator method of the collections returned by all of this class's 'collection view methods' are fail-fast: if the Hashtable 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. The Enumerations returned by Hashtable's keys and elements methods are not fail-fast.

Generate ssh key ubuntu 17.10. 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.

As of the Java 2 platform v1.2, this class was retrofitted to implement the Map interface, making it a member of the Java Collections Framework. Unlike the new collection implementations, Hashtable is synchronized. If a thread-safe implementation is not needed, it is recommended to use HashMap in place of Hashtable. If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable.