Heading

Thursday, July 4, 2013

Sorting by Name Using Comparable Interface


import java.util.ArrayList;
import java.util.Collections;

public class Manager1 implements Comparable<Object>
{
int age;
String name;
Manager1(int age,String name)
{
    this.age=age;
    this.name=name;
}
public String toString()
{
    return "age:" +age+" "+ "name:" +name;
}
public int compareTo(Object o)
{
    return ((Manager1)o).age-age;
}
public static void main(String[] args)
{
    ArrayList<Manager1> list=new ArrayList<Manager1>();
    list.add(new Manager1(60,"xyz"));
    list.add(new Manager1(10,"abc"));
    list.add(new Manager1(20,"chaitu"));
    Collections.sort(list);
    System.out.println(list);
   
   
}
}

Output :

[age:60 name:xyz, age:20 name:chaitu, age:10 name:abc]

No comments:

Post a Comment