Tuesday, 31 December 2013

Map in Java

Map

public interface Map<KEY,VALUE>


  • 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
  • Maps are not collections because they do not implement the Collection interface

 


Map interface includes methods
  • void clear()
  • boolean containsKey(Object k)    
  • boolean containsValue(Object v)
  • Set entrySet()
  • boolean equals(Object obj)
  • Object get(Object k)
  • int hashCode()
  • boolean isEmpty()
  • Set keySet() 
  • Object put(Object k, Object v)
  • void putAll(Map m)
  • Object remove(Object k)
  • int size()
  • Collection values()

SortedMap Interface
  •  Extends Map.
  • It ensures that entries are maintained in ascending key order.

Methods Declared are:
  • Comparator comparetor()
  • Object firstKey()
  • SortedMap headMap(Object end)
  • Object lastKey()
  • SortedMap subMap(Object start, Object end)
  • SortedMap tailMap(Object start) 

The Map.Entry Interface
  • Used to Obtain Collection view of map.
  • EntrySet() of Map interface return a set containing the map entries
 Methods declared in Map.Entry interface
  • Boolean equals(Object obj)
  • Object getKey()
  • Object getValue()
  • Int hashCode()
  • Object setValue(Object v)

The Map Classes

The following are the classes that can be used for Maps
  • AbstractMap           implements Map interface
  • HashMap                extends AbstractMap
  • TreeMap                 extends AbstractMap
  • LinkedHashMap      extends HashMap
  • WeakHashMap        extends AbstractMap
  • IdentityHashMap     extends AbstractMap

AbstractMap class

public abstract class AbstractMap<K,V>
extends Object
implements Map<K,V>
Super class of all concrete map implementatoin

Methods 

void    clear()Removes all of the mappings from this map (optional operation)

protected Object    clone()
Returns a shallow copy of this AbstractMap instance: the keys and values themselves are not cloned.

boolean    containsKey(Object key)
Returns true if this map contains a mapping for the specified key.

boolean    containsValue(Object value)Returns true if this map maps one or more keys to the specified value.

abstract Set<Map.Entry<K,V>>    entrySet()
Returns a Set view of the mappings contained in this map.

boolean    equals(Object o)
Compares the specified object with this map for equality.

V    get(Object key)
Returns the value to which the specified key is mapped, or null if this map contains no mapping for the key.

int    hashCode()
Returns the hash code value for this map.

boolean    isEmpty()
Returns true if this map contains no key-value mappings.

Set<K>    keySet()
Returns a Set view of the keys contained in this map.

V    put(K key, V value)
Associates the specified value with the specified key in this map (optional operation).

void    putAll(Map<? extends K,? extends V> m)Copies all of the mappings from the specified map to this map (optional operation).

V    remove(Object key)
Removes the mapping for a key from this map if it is present (optional operation).

int    size()
Returns the number of key-value mappings in this map.

String    toString()
Returns a string representation of this map.

Collection<V>    values()
Returns a Collection view of the values contained in this map.



HashMap Class

Constructors
 

HashMap()
 

HashMap(Map m)
 

HashMap(int capacity)
 

HashMap(int capacity, float fillRatio)


  • HashMap extends AbstractMap
  • HashMap does not add any methods of its own
  • HashMap does not guarantee the order of its element


TreeMap Class
  • TreeMap provides efficient means of storing key/value pairs in sorted order.
  • TreeMap guarantees that its elements will be stored in ascending key order
  •  TreeMap implements SortedMap and extends AbstractMap
  • TreeMap does not define any methods of its own

Constructors
 

TreeMap()
 

TreeMap(Comparator comp)
 

TreeMap(Map m)
 

TreeMap(SortedMap sm)



LinkedHashMap Class

Allows insertion order iteration

Constructors
 
LinkedHashMap()


LinkedHashMap(Map m)
 

LinkedHashMap(int capacity)
 

LinkedHashMap(int capacity, float fillRatio)
 

LinkedHashMap(int capacity, float fillRatio, boolean order)



LinkedHashMap adds one method

Protected boolean removeEldestEntry(Map.Entry e)

  • This method is called by put() and putAll()
  • The oldest entry is passed in e
  • By default it retrun false and does nothing
  • If override, then you can have LinkedHashMap remove the oldest entry in the map
  • To remove retrun true
  • To keep return false

WeakHashMap Class

WeakHashMap is an implementation of the Map interface that stores only weak references to its keys

Storing only weak references allows a key-value pair to be garbagecollected when its key is no longer referenced outside of the WeakHashMap


IdentityHashMap Class

This class implements AbstractMap. It is similar to HashMap except that it uses reference equality when comparing elements

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys

Monday, 30 December 2013

Java Calendar Demo

/**
 *
 */
package com;

import java.util.Calendar;
import java.util.GregorianCalendar;

/**
 * @author Ali
 *
 */
public class MainClass {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String months[] = {
                "Jan", "Feb", "Mar", "Apr",
                "May", "Jun", "Jul", "Aug",
                "Sep", "Oct", "Nov", "Dec"};
        Calendar calendar = Calendar.getInstance();
        System.out.println("Calendar Object is as follows:");
        System.out.println(calendar);
        System.out.println("Month : "+calendar.get(Calendar.MONTH));
        System.out.print("Date: ");
        System.out.print(months[calendar.get(Calendar.MONTH)]);
        System.out.print(" " + calendar.get(Calendar.DATE) + " ");
        System.out.println(calendar.get(Calendar.YEAR));
        System.out.print("Time: ");
        System.out.print(calendar.get(Calendar.HOUR) + ":");
        System.out.print(calendar.get(Calendar.MINUTE) + ":");
        System.out.println(calendar.get(Calendar.SECOND));
        // Set the time and date information and display it.
        calendar.set(Calendar.HOUR, 10);
        calendar.set(Calendar.MINUTE, 29);
        calendar.set(Calendar.SECOND, 22);
        System.out.print("Updated time: ");
        System.out.print(calendar.get(Calendar.HOUR) + ":");
        System.out.print(calendar.get(Calendar.MINUTE) + ":");
        System.out.println(calendar.get(Calendar.SECOND));
       
       
        int year;
        System.out.println("Gregorian Calendar");
        GregorianCalendar gcalendar = new GregorianCalendar();
        // Display current time and date information.
        System.out.print("Date: ");
        System.out.print(months[gcalendar.get(Calendar.MONTH)]);
        System.out.print(" " + gcalendar.get(Calendar.DATE) + " ");
        System.out.println(year = gcalendar.get(Calendar.YEAR));
        System.out.print("Time: ");
        System.out.print(gcalendar.get(Calendar.HOUR) + ":");
        System.out.print(gcalendar.get(Calendar.MINUTE) + ":");
        System.out.println(gcalendar.get(Calendar.SECOND));
        // Test if the current year is a leap year
        if(gcalendar.isLeapYear(year))
        {
            System.out.println("The current year is a leap year");
        }
        else
        {
            System.out.println("The current year is not a leap year");
        }
    }
}


/*
Output:
Calendar Object is as follows:
java.util.GregorianCalendar[time=1382378159963,areFieldsSet=true,areAllFieldsSet=true,lenient=true,zone=sun.util.calendar.ZoneInfo[id="Asia/Calcutta",offset=19800000,dstSavings=0,useDaylight=false,transitions=6,lastRule=null],firstDayOfWeek=1,minimalDaysInFirstWeek=1,ERA=1,YEAR=2013,MONTH=9,WEEK_OF_YEAR=43,WEEK_OF_MONTH=4,DAY_OF_MONTH=21,DAY_OF_YEAR=294,DAY_OF_WEEK=2,DAY_OF_WEEK_IN_MONTH=3,AM_PM=1,HOUR=11,HOUR_OF_DAY=23,MINUTE=25,SECOND=59,MILLISECOND=963,ZONE_OFFSET=19800000,DST_OFFSET=0]
Month : 9
Date: Oct 21 2013
Time: 11:25:59
Updated time: 10:29:22
Gregorian Calendar
Date: Oct 21 2013
Time: 11:25:59
The current year is not a leap year

*/