1
9
10 public class TaulukkoGen<TYPE> {
11 public static class TaulukkoTaysiException extends Error {
12 TaulukkoTaysiException(String viesti) { super(viesti); }
13 }
14
15 private TYPE alkiot[];
16 private int lkm;
17
18 public TaulukkoGen() {
19 this(10);
20 }
21
22 public TaulukkoGen(int koko) {
23 alkiot = (TYPE [])new Object[koko];
24 }
26
27 public void lisaa(TYPE i) throws TaulukkoTaysiException {
28 if ( lkm >= alkiot.length ) throw new TaulukkoTaysiException("Tila loppu");
29 alkiot[lkm++] = i;
30 }
31
32 public String toString() {
33 StringBuffer s = new StringBuffer("");
34 for (int i=0; i<lkm; i++)
35 s.append(" " + alkiot[i]);
36 return s.toString();
37 }
38
39 public void set(int i, TYPE alkio) throws IndexOutOfBoundsException {
40 if ( ( i < 0 ) || ( lkm <= i ) ) throw new IndexOutOfBoundsException("i = " + i);
41 alkiot[i] = alkio;
42 }
43
44 public TYPE get(int i) throws IndexOutOfBoundsException {
45 if ( ( i < 0 ) || ( lkm <= i ) ) throw new IndexOutOfBoundsException("i = " + i);
46 return alkiot[i];
47 }
48
49 public static void main(String[] args) {
50
51 TaulukkoGen<Integer> luvut = new TaulukkoGen<Integer>();
52
53
54 Integer oma = new Integer(7);
55 try {
56 luvut.lisaa(0); luvut.lisaa(2);
57 luvut.lisaa(99); luvut.lisaa(oma);
59 } catch ( TaulukkoTaysiException e ) {
60 System.out.println("Virhe: " + e.getMessage());
61 }
62 System.out.println(luvut);
63 luvut.set(1,4);
64 luvut.set(3,88);
65 oma = luvut.get(3);
66 System.out.println(luvut);
67 int luku = luvut.get(2); System.out.println("Paikassa 2 on " + luku);
69 try {
70 }
72 catch (IndexOutOfBoundsException e) {
73 System.out.println("Virhe: " + e.getMessage());
74 }
75
76
77 TaulukkoGen<String> sanat = new TaulukkoGen<String>(); sanat.lisaa("kissa");
79 sanat.lisaa("koira");
80 sanat.lisaa("kana");
81
82 System.out.println(sanat.toString());
83
84 }
85 }
86