01: /*
02: * Copyright 2001-2007 Geert Bevin <gbevin[remove] at uwyn dot com>
03: * Distributed under the terms of either:
04: * - the common development and distribution license (CDDL), v1.0; or
05: * - the GNU Lesser General Public License, v2.1 or later
06: * $Id: SortListComparables.java 3634 2007-01-08 21:42:24Z gbevin $
07: */
08: package com.uwyn.rife.tools;
09:
10: import java.util.List;
11:
12: /**
13: * Extends the <code>Sort</code> class to implement the features that are
14: * needed to sort an <code>List</code> datastructure containing only
15: * objects that implement the <code>Comparable</code> interface.
16: *
17: * @author Geert Bevin (gbevin[remove] at uwyn dot com)
18: * @version $Revision: 3634 $
19: * @see Sort
20: * @since 1.0
21: */
22: public class SortListComparables extends Sort {
23: /**
24: * Starts the sorting of the entire ArrayList.
25: *
26: * @param dataToSort An <code>ArrayList</code> instance that has to be
27: * sorted.
28: *
29: * @since 1.0
30: */
31: public final void sort(List<? extends Comparable> dataToSort) {
32: if (null == dataToSort)
33: throw new IllegalArgumentException(
34: "dataToSort can't be null");
35:
36: if (dataToSort.size() > 0) {
37: quickSort(dataToSort, 0, dataToSort.size() - 1, true);
38: }
39: }
40:
41: /**
42: * Starts the sorting of the entire ArrayList.
43: *
44: * @param dataToSort An <code>ArrayList</code> instance that has to be
45: * sorted.
46: * @param ascending true of the data has to be sorted in an ascending
47: * fashion and false otherwise
48: *
49: * @since 1.0
50: */
51: public final void sort(List<? extends Comparable> dataToSort,
52: boolean ascending) {
53: if (null == dataToSort)
54: throw new IllegalArgumentException(
55: "dataToSort can't be null");
56:
57: if (dataToSort.size() > 0) {
58: quickSort(dataToSort, 0, dataToSort.size() - 1, ascending);
59: }
60: }
61:
62: protected void swap(Object dataToSort, int position1, int position2) {
63: List data_to_sort = (List) dataToSort;
64: Object element1 = data_to_sort.get(position1);
65: Object element2 = data_to_sort.get(position2);
66:
67: data_to_sort.add(position1 + 1, element2);
68: data_to_sort.remove(position1);
69: data_to_sort.add(position2 + 1, element1);
70: data_to_sort.remove(position2);
71: }
72:
73: protected Object elementAt(Object dataToSort, int position) {
74: return ((List) dataToSort).get(position);
75: }
76:
77: protected int compare(Object element1, Object element2) {
78: return ((Comparable) element1).compareTo((Comparable) element2);
79: }
80: }
|