samples/delegatingwriterfinal/src-api2.0/api/CharSeq.java
author Jaroslav Tulach <jtulach@netbeans.org>
Sat, 14 Jun 2008 09:53:06 +0200
changeset 65 4db7ceebd2b3
permissions -rw-r--r--
Nonsubclassable Writer example
     1 package api;
     2 
     3 /**
     4  *
     5  * @author Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     6  */
     7 final class CharSeq implements CharSequence {
     8     final char[] arr;
     9     final int off;
    10     final int len;
    11     final int c;
    12     
    13     public CharSeq(int c) {
    14         this.arr = null;
    15         this.off = 0;
    16         this.len = 1;
    17         this.c = c;
    18     }
    19 
    20     public CharSeq(char[] arr, int off, int len) {
    21         this.arr = arr;
    22         this.off = off;
    23         this.len = len;
    24         this.c = -1;
    25     }
    26 
    27     public int length() {
    28         return arr == null ? 1 : len;
    29     }
    30 
    31     public char charAt(int index) {
    32         if (index < 0) {
    33             throw new IndexOutOfBoundsException();
    34         }
    35         if (arr == null) {
    36             if (index > 0) {
    37                 throw new IndexOutOfBoundsException();
    38             }
    39             return (char)c;
    40         } else {
    41             if (index >= len) {
    42                 throw new IndexOutOfBoundsException();
    43             }
    44             return arr[off + index];
    45         }
    46     }
    47 
    48     public CharSequence subSequence(int start, int end) {
    49         if (end >= this.len) {
    50             throw new IndexOutOfBoundsException();
    51         }
    52         char[] array = arr == null ? new char[]{ (char)c } : arr;
    53         return new CharSeq(array, off + start, off + end);
    54     }
    55 
    56 }