import java.util.*; class Student { int rollno; String name; String phone; } class MyComp implements Comparator { public int compare(Object o1, Object o2) { Student s1, s2; s1 = (Student) o1; s2 = (Student) o2; int c; if(s1.rollno < s2.rollno) c = -1; else if (s1.rollno > s2.rollno) c = 1; else c = 0; return c; } } class MyComp1 implements Comparator { public int compare(Object o1, Object o2) { Student s1, s2; s1 = (Student) o1; s2 = (Student) o2; int c; int x = (s1.name).compareTo(s2.name); return x; } } class CompDemo { public static void main(String args[]) { // Create a tree set. TreeSet ts = new TreeSet(new MyComp1()); // Add elements to the tree set. Student s1 = new Student(); s1.rollno = 1; s1.name = "Rahul"; s1.phone = "2590381"; Student s2 = new Student(); s2.rollno = 5; s2.name = "Devesh"; s2.phone = "9829059033"; Student s3 = new Student(); s3.rollno = 3; s3.name = "Rakesh"; s3.phone = "2590381"; Student s4 = new Student(); s4.rollno = 2; s4.name = "Manohar"; s4.phone = "2590381"; Student s5 = new Student(); s5.rollno = 4; s5.name = "Prateek"; s5.phone = "2590381"; ts.add(s1); ts.add(s2); ts.add(s3); ts.add(s4); ts.add(s5); // Display the elements. Iterator<Student> i = ts.iterator(); while(i.hasNext()) { Student s = i.next(); System.out.println(s.rollno +", "+ s.name + ", " +s.phone); } } }
Comments
Post a Comment