Sunday, 26 August 2012

Add a Object of Class using TreeSet

When we add an Object of a class in Using TreeSet then it accept it but when we add  more than one object of a class then it throws an exception because TreeSet is unable to compare those object that are added in it. To overcome this problem we have to implements the Comparable interface in that class that has to be added in the treeset as follows:

1. Create a class Student and implements the Comparable Interface.

public class Student implements Comparable<Student> {
    String name;
    int age;

    public Student(String n, int a) {
        this.name = n;
        this.age = a;
    }

    @Override
    public int compareTo(Student std) {
        int i;
        i = this.age - std.age;
        return i;
    }
    public String toString(){
        return "Name:"+name+" "+"Age:"+age;
    }

}
2. Now Create other class named it TreeSetExample

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample{
    public static void main(String args[]) throws ClassCastException {
        Set<Student> students = new TreeSet<Student>();

        students.add(new Student("Vikash", 21));
        students.add(new Student("Manohar", 32));
        students.add(new Student("Kittoo", 7));
        Iterator<Student> itr = students.iterator();
        while (itr.hasNext()) {
            Student std = itr.next();
            System.out.println(std);
        }
    }

}

No comments:

Post a Comment