1 9 package javolution.xml.pull; 10 11 import j2me.lang.CharSequence; 12 import j2me.lang.Comparable; 13 import javolution.realtime.ObjectFactory; 14 import javolution.util.FastComparator; 15 16 24 final class CharSequenceImpl implements CharSequence, Comparable { 25 26 29 static final ObjectFactory FACTORY = new ObjectFactory() { 30 protected Object create() { 31 return new CharSequenceImpl(); 32 } 33 }; 34 35 38 static final CharSequenceImpl EMPTY = new CharSequenceImpl(""); 39 40 43 char[] data; 44 45 48 int offset; 49 50 53 int length; 54 55 58 CharSequenceImpl() { 59 } 60 61 66 CharSequenceImpl(String string) { 67 data = string.toCharArray(); 68 offset = 0; 69 length = string.length(); 70 } 71 72 78 public int length() { 79 return length; 80 } 81 82 90 public char charAt(int index) { 91 if ((index < 0) || (index >= length)) 92 throw new IndexOutOfBoundsException("index: " + index); 93 return data[offset + index]; 94 } 95 96 107 public CharSequence subSequence(int start, int end) { 108 if ((start < 0) || (end < 0) || 109 (start > end) || (end > this.length())) 110 throw new IndexOutOfBoundsException(); 111 CharSequenceImpl chars = (CharSequenceImpl) FACTORY.object(); 112 chars.data = data; 113 chars.offset = offset + start; 114 chars.length = end - start; 115 return chars; 116 } 117 118 125 public String toString() { 126 return new String(data, offset, length); 127 } 128 129 137 public int hashCode() { 138 int h = 0; 139 for (int i = 0, j = offset; i < length; i++) { 140 h = 31 * h + data[j++]; 141 } 142 return h; 143 } 144 145 153 public boolean equals(Object that) { 154 if (that instanceof CharSequenceImpl) { 155 return equals((CharSequenceImpl) that); 156 } else if (that instanceof String) { return equals((String) that); 158 } else if (that instanceof CharSequence) { 159 return equals((CharSequence) that); 160 } else { 161 return false; 162 } 163 } 164 165 173 public boolean equals(CharSequenceImpl that) { 174 if (that == null) 175 return false; 176 if (this.length != that.length) 177 return false; 178 final char[] thatData = that.data; 179 final int end = offset + length; 180 for (int i = offset, j = that.offset; i < end;) { 181 if (data[i++] != thatData[j++]) 182 return false; 183 } 184 return true; 185 } 186 187 194 public boolean equals(String str) { 195 if (str == null) 196 return false; 197 if (this.length != str.length()) 198 return false; 199 for (int i = 0, j = offset; i < length;) { 200 if (data[j++] != str.charAt(i++)) 201 return false; 202 203 } 204 return true; 205 } 206 207 215 public boolean equals(CharSequence chars) { 216 if (chars == null) 217 return false; 218 if (this.length != chars.length()) 219 return false; 220 for (int i = 0, j = offset; i < length;) { 221 if (data[j++] != chars.charAt(i++)) 222 return false; 223 224 } 225 return true; 226 } 227 228 237 public int compareTo(Object seq) { 238 return FastComparator.LEXICAL.compare(this, seq); 239 } 240 } | Popular Tags |