Hash Map Example using Generic


In this Sample program you can get know how to use hash map by Generic
HashMapSample.java
// Comment

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

/**
*
* @author allinalljava.blogspot.com
*/
public class HashMapSample {
public static void main (String [] args)
{

Map<String, Object> m = new HashMap<String, Object>();//In the has map has both object of a class and string.
Employee<String ,Double> e = new Employee<String ,Double> ("ram", 50000.0);
m.put ("123", e);
e = new Employee<String ,Double> ("ganes", 30000.0);
m.put ("456", e);
Employee<String ,String> total = new Employee<String ,String> ("Generic"," Example");
m.put ("This is Sample ", total);
Set entries = m.entrySet ();
Iterator iter = entries.iterator ();
while (iter.hasNext ())
{
Map.Entry me = (Map.Entry) iter.next ();
System.out.print (me.getKey () + " ");
e = (Employee<String, Double>) me.getValue ();
System.out.println (e.getName () + " " + e.getSalary ());
}
System.out.println ("Map size = " + m.size ());
System.out.println ("Empty: " + m.isEmpty ());
m.clear ();
System.out.println ("Map size = "+ m.size ());
System.out.println ("Empty: " + m.isEmpty ());
}
}


Employee.java
//Comment

/*
* To change this template, choose Tools | Templates

* and open the template in the editor.
*/


/**
*
* @author allinalljava.blogspot.com
*/
import java.util.*;
class Employee<T,R>
{
private T name;

private R salary;

Employee (T t, R r){
this.name = t;
this.salary = r;
}
public R getSalary() {
    return salary;
}
public void setSalary(R salary) {
    this.salary = salary;

}
public T getName() {
    return name;
}
public void setName(T name) {
    this.name = name;
}


}



Output 123
 ram 50000.0
This is Sample Generic Example
456 ganes 30000.0
Map size = 3
 Empty: false
Map size = 0
Empty: true
raja P Web Developer

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...