Sep 12, 2008

Comparator implementation in sorting

I often forget the comparator implementation result.
This comparator will cause the list to sorted in increasing order of elements.



1 class MyComparator implements Comparator {

2 public int compare(Object o1, Object o2) {

3 MyObject co1 = (MyObject) o1;
4 MyObject co2 = (MyObject) o2;

5 double margin = co1.getRank() - co2.getRank();

6 int result = (int) margin;
7 return result;

8 }
9 }



Here is the test code (in JAVA) that shows the result
------------------------------------------------------------------------------------



1 import java.util.ArrayList;
2 import java.util.Collections;

3 import java.util.Comparator;
4
5 public class Test {

6 public static void main(String [] args) {

7
8 ArrayList <myobject> data = new ArrayList<myobject>();

9 MyObject a = new MyObject(2,"B");

10 data.add(a);
11 data.add(new MyObject(3,"C"));

12 data.add(new MyObject(6,"F"));

13 data.add(new MyObject(26,"Z"));

14 data.add(new MyObject(24,"X"));

15 data.add(new MyObject(25,"Y"));

16 Collections.sort(data, new MyComparator());
17 System.out.println("this is a test project.");

18 for (int i=0; i<data.size(); i++) {

19 System.out.println("Object " + i + " is " + ((MyObject)data.get(i)).getY());

20
21 }
22 }
23
24 }
25

26 class MyObject {
27 int x;
28 String y;

29 MyObject(int x, String y) {
30 this.x = x;

31 this.y = y;
32 }
33 public int getX() {

34 return x;
35 }
36 public String getY() {

37 return y;
38 }
39
40 }

41
42 class MyComparator implements Comparator {
43 public int compare(Object o1, Object o2) {

44 MyObject co1 = (MyObject) o1;
45 MyObject co2 = (MyObject) o2;

46 double margin = co1.getX() - co2.getX(); // increasing order

47 //double margin = co2.getX() - co1.getX(); // decreasing order
48 int result = (int) margin;

49 return result;
50 }
51 }


No comments:

Down with the Dictatorship!

    "Let them hate me, so that they fear me" - Caligula 41AD