Sunday 13 April 2014

Map Interface

A Map is an object that maps keys to values. A map cannot contain duplicate keys: Each key can map to at most one value.

Roll Number Name
123 Krishna
124 Ram
125 Anil
126 Kiran

In the above table, Roll number is the key, which maps to student name. I.e, Roll Number 123 maps to the student name Krishna, 126 maps to the student name Kiran.

public interface Map<K,V> {

    int size();
    boolean isEmpty(); 
    boolean containsKey(Object key);
    boolean containsValue(Object value);
    V get(Object key);
    V put(K key, V value);
    V remove(Object key);
    void putAll(Map<? extends K, ? extends V> m);
    void clear();
    Set<K> keySet();
    Collection<V> values();
    Set<Map.Entry<K, V>> entrySet();
  
    interface Entry<K,V> { 
        K getKey(); 
        V getValue();
        V setValue(V value);
        boolean equals(Object o);
        int hashCode();
    }
  
    boolean equals(Object o);
    int hashCode();
}

HashMap, TreeMap, and LinkedHashMap are the General Implementations of the Map interface.

Example
import java.util.*;
class MapEx{
  public static void main(String args[]){
    Map<Integer, String> studentTable = new TreeMap<> ();
  
  /* Add Student details */
  studentTable.put(123, "Krishna");
  studentTable.put(124, "Ram");
  studentTable.put(125, "Anil");
  studentTable.put(126, "Kiran");
  
  System.out.println("Data in Student Map is");
  System.out.println(studentTable);
  }
}

Output
Data in Student Map is
{123=Krishna, 124=Ram, 125=Anil, 126=Kiran

Classes That timplements Map interface are
AbstractMap, Attributes, AuthProvider, ConcurrentHashMap,
ConcurrentSkipListMap, EnumMap, HashMap, Hashtable, IdentityHashMap, LinkedHashMap, PrinterStateReasons, Properties, Provider, RenderingHints, SimpleBindings, TabularDataSupport, TreeMap, UIDefaults, WeakHashMap




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment