001 /**
002 * Esimerkki dynaamisesta taulukosta Java 1.5:n geneerisyyttä
003 * ja "autoboxingia" käyttäen.
004 * @author Vesa Lappalainen
005 * @version 1.0, 02.03.2002
006 * @version 1.1, 01.03.2005
007 */
008
009 public class TaulukkoGen<TYPE> {
010 public static class TaulukkoTaysiException extends Exception {
011 TaulukkoTaysiException(String viesti) { super(viesti); }
012 }
013
014 private Object alkiot[];
015 private int lkm;
016
017 public TaulukkoGen() {
018 alkiot = new Object[10];
019 }
020
021 public TaulukkoGen(int koko) {
022 alkiot = new Object[koko];
023 }
024
025 public void lisaa(TYPE i) throws TaulukkoTaysiException {
026 if ( lkm >= alkiot.length ) throw new TaulukkoTaysiException("Tila loppu");
027 alkiot[lkm++] = i;
028 }
029
030 public String toString() {
031 StringBuffer s = new StringBuffer("");
032 for (int i=0; i<lkm; i++)
033 s.append(" " + alkiot[i]);
034 return s.toString();
035 }
036
037 public void set(int i, TYPE luku) throws IndexOutOfBoundsException {
038 if ( ( i < 0 ) || ( lkm <= i ) ) throw new IndexOutOfBoundsException("i = " + i);
039 alkiot[i] = luku;
040 }
041
042 public TYPE get(int i) throws IndexOutOfBoundsException {
043 if ( ( i < 0 ) || ( lkm <= i ) ) throw new IndexOutOfBoundsException("i = " + i);
044 return (TYPE)alkiot[i];
045 }
046
047 public static void main(String[] args) {
048 TaulukkoGen<Integer> luvut = new TaulukkoGen<Integer>();
049 try {
050 luvut.lisaa(0); luvut.lisaa(2);
051 luvut.lisaa(99); // Tekee oikeasti luvut.lisaa(new Integer(99));
052 } catch ( TaulukkoTaysiException e ) {
053 System.out.println("Virhe: " + e.getMessage());
054 }
055 System.out.println(luvut);
056 luvut.set(1,4);
057 System.out.println(luvut);
058 int luku = luvut.get(2); // oik: luku = (Integer)(luvut.get(2)).intValue();
059 System.out.println("Paikassa 2 on " + luku);
060 try {
061 luvut.set(21, 4);
062 }
063 catch (IndexOutOfBoundsException e) {
064 System.out.println("Virhe: " + e.getMessage());
065 }
066 }
067 }