Wednesday, July 29, 2009

Sorting a vector of objects using Comparator

Here is something really cool about sorting a Vector of objects. At least it is appealing to me. Let say we have a vector of "Students" objects and we are interested to sort the objects using one of its private fields, say, "StudentID" which is of data type Integer.

The code is as follow:

public static void anyMethod(){
try {
Collections.sort(yourVectorThatContainsObjects, ComparatorName);
} catch (Exception ex) {}
}

public static Comparator<Object> ComparatorName = new Comparator<Object>() {
public int compare(Object resultItem1, Object resultItem2) {
Integer id1 = ((Students)resultItem1).StudentID;
Integer id2 = ((Students)resultItem2).StudentID;
return id2.compareTo(id1);
}
};
The result of this sort is in descending order, eg largest to smallest. However there is a simple trick to sort it in an ascending order. Simply use "return id1.compareTo(id2);" It works for me. I hope it works for you too. Otherwise, please feel free to leave a comment so that I can investigate my code :)

Monday, July 27, 2009

My pet project

This is a brief introduction of my pet project. I hope you find this interesting. I am utilizing Java, jQuery and YouTube API to develop the entire web application. Here is the video.

Wednesday, July 22, 2009

An insightful presentation about Social Media

Friday, July 3, 2009

Greatest Common Divisor (Recursion)

Here's a sample solution to solve the GCD recursively.

public long GCD(long numberA, long numberB) {
if (numberB==0)
return numberA;
else
return GCD(numberB, numberA % numberB);
}
Update: The code is also available in Python in this entry