Using an Instance of an Object as a Key in Hashmap, and Then Access It with Exactly New Object

Using an instance of an object as a key in hashmap, and then access it with exactly new object?

You need to implement hashCode and equals on Key. The default implementation of these methods simply checks for instance equality (in other words, two Objects will only be equal if they are in fact the same object).

Further reading

Effective Java - Methods common to all objects

Storing a new object as the value of a hashmap?

The problem is that your code only specifies that the values in the map are Object. You know more than that, so tell the compiler that information:

HashMap<String, InfoStor> mapper = new HashMap<String, InfoStor>();
mapper.put("NS01", new InfoStor("NS01"));
...

InfoStor value = mapper.get("NS01");
Integer memory = value.getMemory();

Note that it's generally though not always better to use interfaces for the variable types - and you can use the diamond operator for the constructor call, letting the compiler use type inference to fill in the type arguments:

Map<String, InfoStor> mapper = new HashMap<>();
mapper.put("NS01", new InfoStor("NS01"));
...

InfoStor value = mapper.get("NS01");
Integer memory = value.getMemory();

Issue adding object to HashMap having Object as key

There is no add method in Map.Use put instead.

counts.put(s1, 1);

See :- HashMap

HashMap and int as key

You can't use a primitive because HashMap use object internally for the key. So you can only use an object that inherits from Object (that is any object).

That is the function put() in HashMap and as you can see it uses Object for K:

public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}

modCount++;
addEntry(hash, key, value, i);
return null;
}

The expression "k = e.key" should make it clear.

I suggest to use a wrapper like Integer and autoboxing.

Java HashMap returning null when object and value are present

Iterate over the EntrySet of the Map

   for(Map.Entry<Ship,Point2D.Double> e : shipMoves.entrySet(){
if(shipMoves.get(s)!= null){
Point2D.Double pos = e.getValue();
String type = s.getType();
GW.setShipLocation(pos, type);
s.setPosition(pos.x, pos.y);
Ships.add(s);
}
}

How does a Java HashMap handle different objects with the same hash code?

A hashmap works like this (this is a little bit simplified, but it illustrates the basic mechanism):

It has a number of "buckets" which it uses to store key-value pairs in. Each bucket has a unique number - that's what identifies the bucket. When you put a key-value pair into the map, the hashmap will look at the hash code of the key, and store the pair in the bucket of which the identifier is the hash code of the key. For example: The hash code of the key is 235 -> the pair is stored in bucket number 235. (Note that one bucket can store more then one key-value pair).

When you lookup a value in the hashmap, by giving it a key, it will first look at the hash code of the key that you gave. The hashmap will then look into the corresponding bucket, and then it will compare the key that you gave with the keys of all pairs in the bucket, by comparing them with equals().

Now you can see how this is very efficient for looking up key-value pairs in a map: by the hash code of the key the hashmap immediately knows in which bucket to look, so that it only has to test against what's in that bucket.

Looking at the above mechanism, you can also see what requirements are necessary on the hashCode() and equals() methods of keys:

  • If two keys are the same (equals() returns true when you compare them), their hashCode() method must return the same number. If keys violate this, then keys that are equal might be stored in different buckets, and the hashmap would not be able to find key-value pairs (because it's going to look in the same bucket).

  • If two keys are different, then it doesn't matter if their hash codes are the same or not. They will be stored in the same bucket if their hash codes are the same, and in this case, the hashmap will use equals() to tell them apart.

HashMap - getting First Key value

You can try this:

 Map<String,String> map = new HashMap<>();
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue();

Keep in mind, HashMap does not guarantee the insertion order. Use a LinkedHashMap to keep the order intact.

Eg:

 Map<String,String> map = new LinkedHashMap<>();
map.put("Active","33");
map.put("Renewals Completed","3");
map.put("Application","15");
Map.Entry<String,String> entry = map.entrySet().iterator().next();
String key= entry.getKey();
String value=entry.getValue();
System.out.println(key);
System.out.println(value);

Output:

 Active
33

Update:
Getting first key in Java 8 or higher versions.

Optional<String> firstKey = map.keySet().stream().findFirst();
if (firstKey.isPresent()) {
String key = firstKey.get();
}

Java Hashmap: How to get key from value?

If you choose to use the Commons Collections library instead of the standard Java Collections framework, you can achieve this with ease.

The BidiMap interface in the Collections library is a bi-directional map, allowing you to map a key to a value (like normal maps), and also to map a value to a key, thus allowing you to perform lookups in both directions. Obtaining a key for a value is supported by the getKey() method.

There is a caveat though, bidi maps cannot have multiple values mapped to keys, and hence unless your data set has 1:1 mappings between keys and values, you cannot use bidi maps.


If you want to rely on the Java Collections API, you will have to ensure the 1:1 relationship between keys and values at the time of inserting the value into the map. This is easier said than done.

Once you can ensure that, use the entrySet() method to obtain the set of entries (mappings) in the Map. Once you have obtained the set whose type is Map.Entry, iterate through the entries, comparing the stored value against the expected, and obtain the corresponding key.


Support for bidi maps with generics can be found in Google Guava and the refactored Commons-Collections libraries (the latter is not an Apache project). Thanks to Esko for pointing out the missing generic support in Apache Commons Collections. Using collections with generics makes more maintainable code.


Since version 4.0 the official Apache Commons Collections™ library supports generics.

See the summary page of the "org.apache.commons.collections4.bidimap" package for the list of available implementations of the BidiMap, OrderedBidiMap and SortedBidiMap interfaces that now support Java generics.



Related Topics



Leave a reply



Submit