Knowledge Walls
John Peter
Pune, Maharashtra, India
How to use SET Collection with Comparable in Core java with Example
2112 Views
SetCollection with Comparable interface 
Set Interface assures unique objects in the set. Set expects comparable implements on the object class to make sure custom compareto method tells it is unique object with others.

Example
Set<UserInfo> userInfoSet = new TreeSet<UserInfo>();
SetCollectionExample
import java.util.Set;
import java.util.TreeSet;

class UserInfo implements Comparable<UserInfo> {
    private int rno;
    private String userName;
    
    public int getRno() {
        return rno;
    }
    public void setRno(int rno) {
        this.rno = rno;
    }
    public String getUserName() {
        return userName;
    }
    public void setUserName(String userName) {
        this.userName = userName;
    }
    
    @Override
    public int compareTo(UserInfo o) {
        // TODO Auto-generated method stub
        return (o.rno != this.rno)?1:0;
    }
    public String toString(){
        return this.rno+":"+this.userName;
    }
}
public class SetCollectionExample {
    public static void main(String args[]){    
        Set<UserInfo> dataSet = new TreeSet<UserInfo>();
        {
            UserInfo userInfo = new UserInfo();
            userInfo.setRno(1001);
            userInfo.setUserName("Sarathy");
            
            dataSet.add(userInfo);
        }
        {
            UserInfo userInfo = new UserInfo();
            userInfo.setRno(1002);
            userInfo.setUserName("Gopal");
            
            dataSet.add(userInfo);
        }
        {
            UserInfo userInfo = new UserInfo();
            userInfo.setRno(1001);
            userInfo.setUserName("Sarathy");
            
            dataSet.add(userInfo);
        }
        
        System.out.println(dataSet);
    }
}
Output 
[1001:Sarathy, 1002:Gopal]
  Copyright © 2014 Knowledge walls, All rights reserved
KnowledgeWalls
keep your tutorials and learnings with KnowledgeWalls. Don't lose your learnings hereafter. Save and revise it whenever required.
Click here for more details