Here we’ll know more about one of the challenging java interview question

Rise of Java Collections

➤ Collection implementations in pre JDK 1.2 versions of the Java platform included few data structure classes, but did not contain a collections framework. The standard methods for grouping Java objects were via the array, the Vector, and the Hashtable classes, which unfortunately were not easy to extend, and did not implement a standard member interface.

➤ To address the need for reusable collection data structures, several independent frameworks were developed,the most used being Doug Lea’s Collections package, and ObjectSpace Generic Collection Library (JGL), whose main goal was consistency with the C++ Standard Template Library (STL).

➤ The collections framework was designed and developed primarily by Joshua Bloch, and was introduced in JDK 1.2. It reused many ideas and classes from Doug Lea’s Collections package, which was deprecated as a result. Sun Microsystems chose not to use the ideas of JGL, because they wanted a compact framework, and consistency with C++ was not one of their goals.

➤ Doug Lea later developed a concurrency package, comprising new Collection-related classes. An updated version of these concurrency utilities was included in JDK 5.0 as of JSR 166.

Java collections framework

➤ The Java collections framework is a set of classes and interfaces that implement commonly reusable collection data structures.

A collection is a data structure actually, an object that can hold references to other objects. Usually, collections contain references to objects of any type that has the is a relationship with the type stored in the collection. The collections-framework interfaces declare the operations to be performed generically on various types of collections. Figure ablove lists some of the collections framework interfaces. Several implementations of these interfaces are provided within the framework. You may also provide your own im- plementations.

Some collections-framework interfaces
What are hashing and hashtables (hashmaps)

➤ HashMap and Hashtable store key/value pairs in a hash table. When using a Hashtable or HashMap, we specify an object that is used as a key, and the value that you want linked to that key.The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.

Maps

➤ Maps associate keys to values. The keys in a Map must be unique, but the associated values need not be. If a Map contains both unique keys and unique values, it’s said to implement a one-to-one mapping. If only the keys are unique, the Map is said to implement a many- to-one mapping many keys can map to one value.

➤ Maps differ from Sets in that Maps contain keys and values, whereas Sets contain only values. Three of the several classes that implement interface Map are Hashtable, HashMap and TreeMap. Hashtables and HashMaps store elements in hash tables, and TreeMaps store elements in trees. This section discusses hash tables and provides an example that uses a HashMap to store key–value pairs. Interface SortedMap extends Map and maintains its keys in sorted order either the elements’ natural order or an order specified by a Comparator. Class TreeMap implements SortedMap.

HashMap vs HashTable ⚔️
  1. HashMap is non synchronized. It is not-thread safe and can’t be shared between many threads without proper synchronization code whereas Hashtable is synchronized. It is thread-safe and can be shared with many threads.
    2. HashMap allows one null key and multiple null values whereas Hashtable doesn’t allow any null key or value.
    3. HashMap is generally preferred over HashTable if thread synchronization is not needed
  2. HashTable is synchronized, whereas HashMap is not. This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
  3. HashTable does not allow null keys or values. HashMap allows one null key and any number of null values.
  4. HashMap is much faster and uses less memory than Hashtable as former is unsynchronized . Unsynchronized objects are often much better in performance in compare to synchronized object like Hashtable in single threaded environment.
What is HashMap 🤔

HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs. To access a value one must know its key. HashMap is known as HashMap because it uses a technique called Hashing.Hashing is a technique of converting a large String to small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles.

What are hash-functions

➤ A hash function is any function that can be used to map data of arbitrary size to fixed-size values. The values returned by a hash function are called hash values, hash codes, digests, or simply hashes. The values are used to index a fixed-size table called a hash table. Use of a hash function to index a hash table is called hashing or scatter storage addressing.

Hash functions and their associated hash tables are used in data storage and retrieval applications to access data in a small and nearly constant time per retrieval, and storage space only fractionally greater than the total space required for the data or records themselves. Hashing is a computationally and storage space efficient form of data access which avoids the non-linear access time of ordered and unordered lists and structured trees, and the often exponential storage requirements of direct access of state spaces of large or variable-length keys.

How implement HashMap

HashMap contains an array of Node and Node can represent a class having following objects :

  1. int hash
  2. K key
  3. V value
  4. Node next
Hashing

Hashing is a process of converting an object into integer form by using the method hashCode(). Its necessary to write hashCode() method properly for better performance of HashMap. Here I am taking key of my own class so that I can override hashCode() method to show different scenarios. My Key class is

class Key
{
String key;
Key(String key)
{
this.key = key;
}

@Override
public int hashCode()
{
return (int)key.charAt(0);
}

@Override
public boolean equals(Object obj)
{
return key.equals((String)obj);
}
}

HashMap stores the data in the form of key-value pairs. Each key-value pair is stored in an object of Entry<K, V> class. Entry<K, V> class is the static inner class of HashMap which is defined like below.

class Entry<K, V> {
final K key;
V value;
Entry<K, V> next;

public Entry(K key, V value, Entry<K, V> next) {
this.key = key;
this.value = value;
this.next = next;
}
}
HashMap.put()
/**
* Associates the specified value with the specified key in this map. If the
* map previously contained a mapping for the key, the old value is
* replaced.
*
* @param key
* key with which the specified value is to be associated
* @param value
* value to be associated with the specified key
* @return the previous value associated with key, or null
* if there was no mapping for key. (A null return
* can also indicate that the map previously associated
* null with key.)
*/
public V put(K key, V value) {
if (key == null)
return putForNullKey(value);
int hash = hash(key.hashCode());
int i = indexFor(hash, table.length);
for (Entry 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;
}
HashMap.get()
/**
* Returns the value to which the specified key is mapped, or {@code null}
* if this map contains no mapping for the key.
*
*
* More formally, if this map contains a mapping from a key {@code k} to a
* value {@code v} such that {@code (key==null ? k==null :
* key.equals(k))}, then this method returns {@code v}; otherwise it returns
* {@code null}. (There can be at most one such mapping.)
*
*
* A return value of {@code null} does not necessarily indicate that
* the map contains no mapping for the key; it's also possible that the map
* explicitly maps the key to {@code null}. The {@link #containsKey
* containsKey} operation may be used to distinguish these two cases.
*
* @see #put(Object, Object)
*/
    public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry e = table[indexFor(hash, table.length)]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
When we should use HashMap

➤ Maps are used for when you want to associate a key with a value and Lists are an ordered collection.

➤ Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.

➤ HashMap should be used over ArrayList when there is no use of index and when the data is need to be identified using key value pair.

Key points to Remember
  1. HashMap has a inner class called Entry which stores key-value pairs.
  2. Above Entry object is stored in Entry[ ](Array) called table
  3. An index of table is logically known as bucket and it stores first element of linkedlist
  4. Key object’s hashcode() is used to find bucket of that Entry object.
  5. If two key object ‘s have same hashcode , they will go in same bucket of table array.
  6. Key object ‘s equals() method is used to ensure uniqueness of key object.
  7. Value object ‘s equals() and hashcode() method is not used at all
Conclusion

This post illustrated how hashmap (or hashtable) can be implemented with an array-based linked list.

If you enjoyed this post, I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter or Facebook. Thank you! ^_^

😎I will write about HashMap changes in Java 8 in part 2.😎

How HashMap works in Java? With Animation!! whats new in java8 tutorial?