Saturday, August 13, 2011

Sorting in Blackberry

Sorting vector or arrays is difficult in J2ME because J2ME APIs doesn’t include the collections framwork.
But Blackberry API has sortable collections like SimpleSortingVector or you can use Arrays class sort method also.
The key in sorting is Comparator interface that allows you to specify how the elements should
be compared. Sorting using Comparator is a good example of strategy pattern and the Java idiom for function-pointer-like functionality.

1. Create your Data class.

1. Create your Data class.

  1. class Data {
  2. private String name;
  3. private int age;
  4. public Data(String name, int age) {
  5. this.name = name;
  6. this.age = age;
  7. }
  8. String getName() {
  9. return name;
  10. }
  11. int getAge() {
  12. return age;
  13. }
  14. }
2. Key of sorting method is Comparator that allows you to specify how the elements should
be compared.
Here we will create two implementaion of Coparator one for name and another for age.

  1. class NameComparator implements Comparator {
  2. public int compare(Object o1, Object o2) {
  3. return ((Data) o1).getName().compareTo(((Data) o2).getName());
  4. }
  5. }
  6. class AgeComparator implements Comparator {
  7. public int compare(Object o1, Object o2) {
  8. return ((Data) o1).getAge() - (((Data) o2).getAge());
  9. }
  10. }
3. First we will see the use of SimpleSortingVector.


  • SimpleSortingVector sortingVector = new SimpleSortingVector();
  • sortingVector.addElement(new Data("b", 25));
  • sortingVector.addElement(new Data("a", 31));
  • sortingVector.addElement(new Data("c", 26));
  • sortingVector.setSortComparator(new AgeComparator());
  • sortingVector.setSort(true);
  • Enumeration en = sortingVector.elements();
  • StringBuffer sb = new StringBuffer();
  • while (en.hasMoreElements()) {
  • Data data = (Data) en.nextElement();
  • sb.append(data.getName() + " " + data.getAge() + "\n");
  • }
  • System.out.println(sb);
  • 4. Now we will see the Arrays class sort method.

  • Data[] data = {new Data(“b”,32),new Data(“a”,23),new Data(“c”,34)};
  • Arrays.sort(data, new NameComparator());

  • http://blog.vimviv.com/blackberry/sorting-blackberry/#more-398

    No comments:

    Post a Comment