Showing posts with label Generics. Show all posts
Showing posts with label Generics. Show all posts

Saturday, 18 May 2013

Hashtable example in Java.

In last post we saw difference between a HashMap and a Hashtable. Let us now see what Hashtable is and how do we use it.

If you see the source code implementation of Hashtable it is similar to that of map. Infact Hashtable implements Map interface.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. For more information refer to Hashtable JavaDocs.

public class Hashtable<K,V>
    extends Dictionary<K,V>
    implements Map<K,V>, Cloneable, java.io.Serializable
{...

Lets see how can we use Hashtable.

Code : 

package testCodes;

import java.util.Enumeration;
import java.util.Hashtable;

public class HashtableDemo {
    
    public static void main(String args[])
    {
        Hashtable<String, String> hashTable = new Hashtable<String, String>();
        //Populating Hashtable
        hashTable.put("Name", "John");
        hashTable.put("Country", "USA");
        hashTable.put("Gender", "Male");
        //Printing whole table
        System.out.println("hashTable : " + hashTable);
        //printing individual values
        Enumeration<String> data = hashTable.keys();
        while(data.hasMoreElements())
        {
            String str = (String) data.nextElement();
            System.out.println(str + " : " + hashTable.get(str));
        }
    }    
}

Output :


Understanding the code : 

     Code is very much similar to HashMap usage but has slight variations. Note Hashtable is a class and not an Interface. put() and get() method remain the same as that of HashMap. What is different is the concept of Enumeration. As specified earlier when Hashtable was introduced there was no Collections and hence no iterators. What we had to use was Enumeration. Enumeration is similar to Iterator. We check whether it has more elements using hasMoreElements() function, if yes access the next element using nextElement() function. Note the use of generics remain the same.

Few very common differences between a HashMap and a Hashtable are -
  • Hashtable is synchronized where as HashMap is not.
  • Hashtable does not allow null keys or values whereas HashMap allows one null key and any number of null values.
  • keys() method of Hashtable return Enumeration where as keySet() method of HashTable returns a Set which can be iterated over as it implements Iterable interface - Enumeration does not.

 Related Links

Sunday, 12 May 2013

Simple Map example in Java.

We have learned enough theory on Collections. We also saw a working demo code for ArrayList. In last post we saw why Map interface does not implement Collection framework and in the coming posts we will see how to iterate over the data in Map. But for now lets see a demo code of Map.

Java Code demonstrating Map usage

Code :

package testCodes;

import java.util.HashMap;
import java.util.Map;

public class MapDemo {

    public static void main(String args[]) {
        Map<String, String> persononalData = new HashMap<String, String>();
        // Populating Map with data
        persononalData.put("Name", "John");
        persononalData.put("Country", "USA");
        persononalData.put("Gender", "Male");
        persononalData.put("Age", "18");
        // Printing Map
        System.out.println("Map is " + persononalData);
        // removing data from Map
        persononalData.remove("Gender");
        // Printing Map
        System.out.println("Map is " + persononalData);
        if (Integer.valueOf(persononalData.get("Age")) < 18) {
            System.out.println("You are a minor");
        } else {
            System.out.println("You are a Major");
        }
    }
}

Output :

Understanding the Code :

We create a Map named persononalData to store personal information of some person named John. Note the generics used. Both key-value are of type String. At a later point of time if you try to put another data type(say int) then that is not allowed. You must always decide on the data structure before you start writing you actual code.In this case I am going to store everything as String.
     We then start populating data. We add Name, Country, Age and Gender.Note the function is put(key,value) unlike add(element) in Collections.We then print the Map. Note when we say System.out.println(someMap) internally toString() method is invoked on the corresponding object and is printed to standard output.
   Next we remove an element using .remove(key) method.Again we print out the Map to see the difference. Check out the output screen shot provided above.

Note : All keys in the Map must be Unique i.e you cannot store two different values for the same key. Lets say you do someMap.put("Name","John") and then again you say someMap.put("Name","Sam") then Sam will overwrite John and when you extract data by get("Name") you will get Sam and not John.

  Next we extract age of the person using .get("Age") method. Note this will return you a String. But for comparison purpose you need an integer and hence we convert String to an int using Integer.ValueOf(SomeString) method.In our case age is 18 and hence age<18 will evaluate to be false and else part will get executed. Hence the output shown.

   Hope basic operations in Map are clear. In next post we will see how to iterate over Map to manipulate it's data.

Related Links

Saturday, 4 May 2013

Understanding Iterators in Java

Having some idea about Collections in Java lets see what is an Iterator and what is it used for? As described in post on Java Collection an Iterator object is used to iterate over elements stored in a Collection.

 You know that Collection is an Interface. Even List, Set, Queue are Interfaces which then have their own concrete implementations like ArrayList, HashSet, LinkedList etc. Collection Interface implements another Interface called Iterable.

If you go and open the sour code for Collection Interface in Java you will find -

public interface Collection<E> extends Iterable<E> 

{

 int size();

 boolean isEmpty();

 boolean contains(Object o);

 Iterator<E> iterator();

 Object[] toArray();

 <T> T[] toArray(T[] a);

 boolean add(E e);

 boolean remove(Object o);

 boolean containsAll(Collection<?> c);

 boolean addAll(Collection<? extends E> c);

 boolean removeAll(Collection<?> c);

 boolean retainAll(Collection<?> c);

 void clear();

 boolean equals(Object o);

 int hashCode(); 
} 

and if you go and see what there in Iterable Interface you will find -

public interface Iterable<T> 
{
    Iterator<T> iterator();
}


Iterator is again an interface whose source code is as follows -

public interface Iterator<E> 
{
    boolean hasNext();
    E next();
    void remove();
}


Note :  All these are just Interfaces(abstract functions). Their concrete implementation will be in the first concrete subclass.

Points to Note -
  • We can iterate only in one direction.
  • Iteration can be done only once. This means once we reach end of a series we must get a new iterator to iterate. 

Lets take an example to demonstrate how Iterator works -

package testCodes;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class IteratorDemo {

    public static void main(String[] args) {
       
        List<String> nameList = new ArrayList<String>();
        nameList.add("John");
        nameList.add("Sam");
        nameList.add("kenny");
        nameList.add("Jessica");
       
        Iterator<String> namesIterator = nameList.iterator();
        System.out.println("Printing names");
        while(namesIterator.hasNext())
        {
            System.out.println(namesIterator.next());
        }
    }

}




 Output

Understanding the code

    First we create a ArrayList called nameList and store some values in it. Note the use of Generics. nameList will and should always contain a String. If you try to add any other object Compiler will complaint. Also when you extract any element from the List you will always get a String object.

     Next we get an Iterator from the ArrayList. Note the Syntax. We can get such Iterator from any entity(interface/class) which come under Collection inheritance tree(Remember Collection implements Iterable). So we just need to use .iterator() function to get the respective iterator. Then we can iterate to get the elements. Note .hasNext() checks whether Collection(List/ArrayList in our case) has next element or not where as .next() will actually give you the next element.

Note :  Map and its sub classes/ sub interfaces are not a part of Collections.So you cannot use .iterator() function on it. There are other was to iterate over it's data but we shall cover that separately.

t> UA-39527780-1 back to top