Salesforce : Apex Comparable Interface implementation and example
public with sharing class AtestClass {
class Emp implements Comparable{
public Emp(String name,Integer age ){
this.name = name;
this.age= age;
}
String name{get;set;}
Integer age{get;set;}
public Integer compareTo(object o){
Emp cEmp = (Emp)o;
if( this.name > cEmp.name ){
return 1;
}
else if( this.name < cEmp.name ){
return -1;
}
else{
return 0;
}
}
}
public void createAndSortList() {
List<Emp> lstEmp = new List<Emp>();
lstEmp.add(new Emp('John',30));
lstEmp.add(new Emp('Mike',31));
lstEmp.add(new Emp('John',32));
lstEmp.add(new Emp('John',33));
lstEmp.add(new Emp('Mike',34));
lstEmp.sort();
for(Emp e : lstEmp){
System.debug(e.name+'---'+e.age);
}
}
}
class Emp implements Comparable{
public Emp(String name,Integer age ){
this.name = name;
this.age= age;
}
String name{get;set;}
Integer age{get;set;}
public Integer compareTo(object o){
Emp cEmp = (Emp)o;
if( this.name > cEmp.name ){
return 1;
}
else if( this.name < cEmp.name ){
return -1;
}
else{
return 0;
}
}
}
public void createAndSortList() {
List<Emp> lstEmp = new List<Emp>();
lstEmp.add(new Emp('John',30));
lstEmp.add(new Emp('Mike',31));
lstEmp.add(new Emp('John',32));
lstEmp.add(new Emp('John',33));
lstEmp.add(new Emp('Mike',34));
lstEmp.sort();
for(Emp e : lstEmp){
System.debug(e.name+'---'+e.age);
}
}
}
Comments
Post a Comment