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);
        }
    }

}

Java Thread

Creating a Thread Example


We can create a thread in two ways:

1. Extends the Thread Class
2. Implements the Thread Interface

1. Creating the Thread extending Thread Class


class Test extends Thread{
    Test(){
    super("Thread One");
    }
}
public class ThreadTest2 {
    public static void main(String args[]){
        Test t=new Test();
      
        System.out.println(t);
    }

}
2. Creating the thread implementing the runnable Interface
When we implement the runnable interface then we must override the run() method.

class MyThread implements Runnable{
    String name;
    int number;
public MyThread(String n,int num) {
    this.name=n;
    this.number=num;
   
}

    @Override
    public void run() {
        System.out.println("Hello");
    }
   
    public String toString(){
        return "Thread Name:"+name+":"+"Number:"+number;
    }
}
public class ThreadTest {
public static void main(String args[]){
    MyThread myThread1=new MyThread("Testing Thread",1);
    myThread1.run();
    System.out.println(myThread1);
}
}