/Users/lyon/j4p/src/collections/sortable/SortableVector.java
|
1 package collections.sortable;
2
3 import java.util.Collections;
4 import java.util.Vector;
5 import java.util.Comparator;
6
7
8 public class SortableVector {
9 private final Vector v = new Vector();
10
11 public static void main(String args[]) {
12 testSort();
13
14 }
15 public void copyInto(Object o[]) {
16 v.copyInto(o);
17 }
18 private static void testSort() {
19 SortableVector v = new SortableVector();
20 String s[] = {"tom", "dick", "harry"};
21
22 for (int i = 0; i < s.length; i++)
23 v.addElement(s[i]);
24 v.print();
25 v.sort();
26 v.print();
27 }
28
29 /**
30 * Start looking from the startPoint for the
31 * <code>key</code> and return the location,
32 * if you find it. Return -1 if you do not
33 * find it.
34 *
35 * @param key
36 * @param startPoint
37 * @return
38 */
39 public int find(Comparable key,
40 int startPoint) {
41 if (startPoint >= v.size()) return -1;
42 if (key == null) return -1;
43 for (int i = startPoint; i < v.size(); i++) {
44 Comparable me = elementAt(i);
45 if (me.compareTo(key) == 0) return i;
46 }
47 return -1;
48 }
49
50 public SortableVector() {
51 };
52 public void print() {
53 for (int i = 0; i < v.size(); i++)
54 System.out.println(v.elementAt(i));
55 }
56
57 private void swap(int i, int j) {
58 Object o1 = v.elementAt(i);
59 Object o2 = v.elementAt(j);
60 v.setElementAt(o2, i);
61 v.setElementAt(o1, j);
62 }
63
64 public void bubbleSort() {
65 for (int i = v.size(); --i >= 0;) {
66 for (int j = 0; j < i; j++) {
67 Comparable c1 = (Comparable)
68 v.elementAt(j);
69 Comparable c2 = (Comparable)
70 v.elementAt(j + 1);
71 int c = c1.compareTo(c2);
72 if (c > 0)
73 swap(j, j + 1);
74 }
75 }
76 }
77
78 public boolean isEmpty() {
79 return v.isEmpty();
80 }
81
82 public boolean contains(Comparable o) {
83 return v.contains(o);
84 }
85
86 public Comparable[] toArray() {
87 return (Comparable[]) v.toArray();
88 }
89
90
91 public boolean remove(Comparable o) {
92 return v.remove(o);
93 }
94
95 public boolean add(Comparable o) {
96 return v.add(o);
97 }
98
99 public synchronized int size() {
100 return v.size();
101 }
102
103 public synchronized Comparable elementAt(
104 int index) {
105 return (Comparable) v.elementAt(index);
106 }
107
108 public synchronized void setElementAt(
109 Comparable obj, int index) {
110 v.setElementAt(obj, index);
111 }
112
113 public synchronized void removeElementAt(
114 int index) {
115 v.removeElementAt(index);
116
117 }
118
119 public void sort(Comparator c) {
120 Collections.sort(v,c);
121 }
122
123 public synchronized void addElement(
124 Comparable obj) {
125 v.addElement(obj);
126 }
127
128 public void sort() {
129 Collections.sort(v);
130 }
131 }