1 8 9 package net.sourceforge.chaperon.common; 10 11 import net.sourceforge.chaperon.common.Decoder; 12 13 20 public class SortedCharSet 21 { 22 private char elementCount = 0; 23 private char[] list = new char[10]; 24 25 27 30 public SortedCharSet() {} 31 32 39 public void addChar(char value) 40 { 41 if (list.length<(elementCount+1)) 42 { 43 char[] newList = new char[elementCount+10]; 44 System.arraycopy(list, 0, newList, 0, list.length); 45 list = newList; 46 } 47 48 list[elementCount++] = value; 49 sort(); 50 } 51 52 57 public void addChar(char[] array) 58 { 59 if (list.length<(elementCount+array.length)) 60 { 61 char[] newList = new char[elementCount+array.length]; 62 System.arraycopy(list, 0, newList, 0, list.length); 63 list = newList; 64 } 65 66 System.arraycopy(array, 0, list, elementCount, array.length); 67 elementCount += array.length; 68 sort(); 69 } 70 71 76 public void removeChar(char index) 77 { 78 if (index>=elementCount) 79 throw new ArrayIndexOutOfBoundsException (index); 80 81 elementCount--; 82 if (index<elementCount) 83 System.arraycopy(list, index+1, list, index, elementCount-index); 84 85 list[elementCount] = 0; 86 } 87 88 95 public char getChar(int index) 96 { 97 if (index>=elementCount) 98 throw new ArrayIndexOutOfBoundsException (index); 99 100 return list[index]; 101 } 102 103 public char[] getChar() 104 { 105 char[] newList = new char[elementCount]; 106 System.arraycopy(list, 0, newList, 0, elementCount); 107 return newList; 108 } 109 110 115 public char getCharCount() 116 { 117 return elementCount; 118 } 119 120 127 public int indexOf(char value) 128 { 129 for (char i = 0; i<elementCount; i++) 130 if (list[i]==value) 131 return i; 132 133 return -1; 134 } 135 136 143 public boolean contains(char value) 144 { 145 for (char i = 0; i<elementCount; i++) 146 if (list[i]==value) 147 return true; 148 149 return false; 150 } 151 152 157 public boolean isEmpty() 158 { 159 return (elementCount<=0); 160 } 161 162 165 public void clear() 166 { 167 elementCount = 0; 168 } 169 170 173 private void sort() 174 { 175 char c; 176 boolean modified = false; 177 do 178 { 179 modified = false; 180 181 for (int i = 1; i<elementCount; i++) 182 if (list[i-1]>list[i]) 183 { 184 c = list[i-1]; 185 list[i-1] = list[i]; 186 list[i] = c; 187 188 modified = true; 189 } 190 else if (list[i-1]==list[i]) { 192 if (i<(elementCount-1)) 193 list[i] = list[--elementCount]; 194 else 195 elementCount--; 196 197 modified = true; 198 } 199 } 200 while (modified); 201 } 202 203 208 public String toString() 209 { 210 StringBuffer buffer = new StringBuffer (); 211 212 buffer.append("["); 213 for (char i = 0; i<elementCount; i++) 214 { 215 buffer.append(Decoder.toChar(list[i])); 216 if (i<(elementCount-1)) 217 buffer.append(","); 218 } 219 220 buffer.append("]"); 221 return buffer.toString(); 222 } 223 } 224 | Popular Tags |