Tuesday 26 May 2015

How to storing Java Object In HashSet


import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class HashSetOfObject {
    public static void main(String[] args) {
       
        Set<User> hs = new HashSet<User>();

        hs.add(new User("shivam",1213));
        hs.add(new User("yogesh",8383));
        hs.add(new User("ashwani", 8287));
       
        Iterator<User> itr =hs.iterator();
        while (itr.hasNext()) {
            User user = (User) itr.next();
            System.out.println("userName ="+user.getName()+" userId = "+user.getUserId());
        }
       
       
    }
}

class User{
       
    private String name;
    private int userId;
   
    public User(String name, int userId) {
        super();
        this.name = name;
        this.userId = userId;
    }

    public String getName() {
        return name;
    }

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

    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }
    
}



Output:

userName =ashwani userId = 8287

userName =shivam userId = 1213

userName =yogesh userId = 8383

No comments:

Post a Comment