Showing posts with label store object in hashtable. Show all posts
Showing posts with label store object in hashtable. Show all posts

Thursday, 11 June 2015

How to storing Java Object In HashTable

import java.util.Hashtable;
import java.util.Set;

public class HashTableOfObject {

    public static void main(String[] args) {

        Hashtable<Integer,User> ht = new Hashtable<Integer,User>();
       
        ht.put(1,new User("ankush",100));
        ht.put(2,new User("shivam",200));
        ht.put(3,new User("raja", 500));
        ht.put(5,new User("ram",900));
        ht.put(6,new User("ravi",750));

        /*
         * Returns a Set view of the keys contained in this map.
         */
        Set<Integer> keys =ht.keySet();
       
        for (Integer key : keys) {
           
            /*
             * Returns the value to which the
             * specified key is  mapped, or null if
             *  this map contains no mapping for the key.
             */
            User user = ht.get(key);
            System.out.println(" key ="+key+" id ="+user.getId()+" name ="+user.getName());
        }

       
    }
}

class User {
    private String name;
    private int id;

    public User(String name, int id) {
        super();
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

}

Output:

 key =6 id =750 name =ravi

 key =5 id =900 name =ram

 key =3 id =500 name =raja

 key =2 id =200 name =shivam

 key =1 id =100 name =ankush