import java.util.Arrays;
import java.util.Comparator;
public class SortComparator {
final static int NUMBER_OF_OBJ = 5;
public class MyClass {
String name;
int number;
MyClass(String n, int i){
name = n;
number = i;
}
}
public static void main(String[] args){
System.out.println("Sort Comparator");
SortComparator sortComparator = new SortComparator();
MyClass[] myClassArray = new MyClass[NUMBER_OF_OBJ];
myClassArray[0] = sortComparator.new MyClass("ABC", 9);
myClassArray[1] = sortComparator.new MyClass("Eric", 6);
myClassArray[2] = sortComparator.new MyClass("Java", 7);
myClassArray[3] = sortComparator.new MyClass("Android", 199);
myClassArray[4] = sortComparator.new MyClass("test", -3);
showMyClass(myClassArray);
Arrays.sort(myClassArray, comparatorName);
System.out.println("\nmyClassArray sorted by name");
showMyClass(myClassArray);
Arrays.sort(myClassArray, comparatorNumber);
System.out.println("\nmyClassArray sorted by number");
showMyClass(myClassArray);
}
static Comparator<? super MyClass> comparatorName
= new Comparator<MyClass>(){
public int compare(MyClass obj1, MyClass obj2) {
return String.valueOf(obj1.name).compareTo(obj2.name);
}
};
static Comparator<? super MyClass> comparatorNumber
= new Comparator<MyClass>(){
public int compare(MyClass obj1, MyClass obj2) {
return Integer.valueOf(obj1.number).compareTo(obj2.number);
}
};
static void showMyClass(MyClass[] mc){
for(int i = 0; i < mc.length; i++){
System.out.println(mc[i].name
+ " : "
+ mc[i].number);
}
}
}
Monday, October 17, 2011
Sort array of object using custom Comparator
Example:
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment