KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > exoplatform > services > communication > sms > util > Sort


1 /***************************************************************************
2  * Copyright 2001-2003 The eXo Platform SARL All rights reserved. *
3  * Please look at license.txt in info directory for more license detail. *
4  **************************************************************************/

5 package org.exoplatform.services.communication.sms.util;
6
7 import java.util.ArrayList JavaDoc;
8 import java.util.Collections JavaDoc;
9 import java.util.Comparator JavaDoc;
10 import java.util.Iterator JavaDoc;
11 import java.util.List JavaDoc;
12
13 /**
14  *
15  * @author: Ove Ranheim
16  * @email: oranheim@users.sourceforge.net
17  */

18 public class Sort {
19
20     public static final int ASC = 0;
21     public static final int DESC = 1;
22
23     public Sort() {
24     }
25
26     public static List JavaDoc sort(List JavaDoc list, String JavaDoc fieldName, int order) {
27
28         Collections.sort(list, new SortComparator(fieldName));
29         if (order == Sort.DESC) Collections.reverse(list);
30
31         return list;
32     }
33
34     public static void main(String JavaDoc[] args) {
35         ArrayList JavaDoc list = new ArrayList JavaDoc();
36         list.add(new TestBean("ove", "toyen"));
37         list.add(new TestBean("tuva", "lokka"));
38         list.add(new TestBean("knut", "st.haugen"));
39         list.add(new TestBean("tor-egil", "Ljan"));
40         List JavaDoc sortedList = Sort.sort(list, "name", Sort.DESC);
41         for (Iterator JavaDoc iterator = sortedList.iterator(); iterator.hasNext();) {
42             TestBean myBean = (TestBean) iterator.next();
43             System.out.println(myBean.getName());
44         }
45     }
46
47     static public void putInSorted(List JavaDoc a, Comparator JavaDoc c) {
48         int cnt = 0;
49         for (Iterator JavaDoc iterator = a.iterator(); iterator.hasNext();) {
50             Object JavaDoc temp = (Object JavaDoc) iterator.next();
51
52             int j = cnt++ - 1;
53             for (; j >= 0 && c.compare(temp, a.get(j)) < 0; j--)
54                 a.set(j + 1, a.get(j));
55
56             a.set(j + 1, temp);
57
58         }
59     }
60
61 }
62
63
Popular Tags