Here is an Example to sort list of added objects to an array list using Comparable interface.
import java.util.ArrayList;
import java.util.Collections;
public class Sort1 implements Comparable<Object>
{
int age;
String name;
Sort1(int age,String name)
{
this.age=age;
this.name=name;
}
public String toString()
{
return "age:" +age+" "+ "name:" +name;
}
public int compareTo(Object o)
{
return ((Sort1)o).age-age;
}
public static void main(String[] args)
{
ArrayList<Sort1> list=new ArrayList<Sort1>();
list.add(new Sort1(60,"byz"));
list.add(new Sort1(10,"xbc"));
list.add(new Sort1(20,"ahaitu"));
Collections.sort(list);
System.out.println(list);
}
}
import java.util.ArrayList;
import java.util.Collections;
public class Sort1 implements Comparable<Object>
{
int age;
String name;
Sort1(int age,String name)
{
this.age=age;
this.name=name;
}
public String toString()
{
return "age:" +age+" "+ "name:" +name;
}
public int compareTo(Object o)
{
return ((Sort1)o).age-age;
}
public static void main(String[] args)
{
ArrayList<Sort1> list=new ArrayList<Sort1>();
list.add(new Sort1(60,"byz"));
list.add(new Sort1(10,"xbc"));
list.add(new Sort1(20,"ahaitu"));
Collections.sort(list);
System.out.println(list);
}
}
No comments:
Post a Comment