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.
- class Data {
- private String name;
- private int age;
- public Data(String name, int age) {
- this.name = name;
- this.age = age;
- }
- String getName() {
- return name;
- }
- int getAge() {
- return age;
- }
- }
be compared.
Here we will create two implementaion of Coparator one for name and another for age.
- class NameComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return ((Data) o1).getName().compareTo(((Data) o2).getName());
- }
- }
- class AgeComparator implements Comparator {
- public int compare(Object o1, Object o2) {
- return ((Data) o1).getAge() - (((Data) o2).getAge());
- }
- }
http://blog.vimviv.com/blackberry/sorting-blackberry/#more-398
No comments:
Post a Comment