Sunday, July 22, 2012

Sample code on how to set the value in a HashMap and retrieve it back


Try out these two programs.... 
(2a)
package pack1;
import java.io.*;
import java.util.*;
import pack1.Employee;

public class HashMapTest {
      public static void main(String[] args) {
            int i = 0;
            String j = i + "";     
            HashMap hashmap = new HashMap();
            i++;
            for(i=1;i<=3;i++)
            {
                  j = i+"A";
                  hashmap.put(i, new Employee(i,j));
            }
            Iterator it = hashmap.keySet().iterator();
            while(it.hasNext())
            {
                  int s1 = (Integer)it.next();
                  Employee e1 = (Employee)hashmap.get(s1);
                  System.out.println("For the Integer Reference " + e1.getIntegerRef() + " the Name Reference is " + e1.getNameDef());
                  //System.out.println("Get the Integer Reference " + e1.getIntegerRef());
                  //System.out.println("Get the Name Reference " + e1.getNameDef());
            }
      }
}

(2b)
package pack1;
import java.util.*;
import java.io.*;

class Employee
{
      private int integerRef = 0;
      private String nameDef = "";
      public Employee(int integerRef, String nameDef)
      {
            this.integerRef = integerRef;
            this.nameDef = nameDef;
      }
      public int getIntegerRef()
      {
            return integerRef;
      }
      public String getNameDef()
      {
            return nameDef;
      }
}

No comments:

Post a Comment