Use []
to access element in the array. But do not forget about throwing required exception, like it declared in CharSequence
documentation (if you access not correct element in an array, another type of exception will be thorwn).
public class AsciiCharSequence implements CharSequence {
private static final char[] EMPTY_ARRAY = new char[0];
private final char[] arr;
public AsciiCharSequence(char[] arr) {
this.arr = arr == null || arr.length == 0 ? EMPTY_ARRAY : Arrays.copyOf(arr, arr.length);
}
private AsciiCharSequence(char[] arr, int start, int end) {
this.arr = arr == null || arr.length == 0 || start == end ? EMPTY_ARRAY : Arrays.copyOfRange(arr, start, end);
}
@Override
public int length() {
return arr.length;
}
@Override
public char charAt(int i) {
if (i < 0 || i >= length())
throw new IndexOutOfBoundsException();
return arr[i];
}
@Override
public AsciiCharSequence subSequence(int start, int end) {
if (start < 0 || end < 0)
throw new IndexOutOfBoundsException();
if (end > length())
throw new IndexOutOfBoundsException();
if (start > end)
throw new IndexOutOfBoundsException();
return new AsciiCharSequence(arr, start, end);
}
@Override
public String toString() {
return IntStream.range(0, arr.length).mapToObj(i -> String.valueOf(arr[i])).collect(Collectors.joining());
}
}