|
1 | 1 | package lec7_lists4;
|
2 | 2 |
|
3 |
| -public class AList { |
| 3 | +public class AList<Glorp> { |
| 4 | + private Glorp[] items; |
4 | 5 | private int size;
|
5 |
| - private int[] items; |
6 | 6 |
|
7 | 7 | public AList() {
|
8 | 8 | size = 0;
|
9 |
| - items = new int[100]; |
| 9 | + items = (Glorp[]) new Object[100]; |
| 10 | + } |
| 11 | + // 0, 0, 0, 0, 0, 0, 0, ... |
| 12 | + // 3, 0, 0, 0, 0, 0, 0, |
| 13 | + // 3, 7, 0, 0, 0, 0, 0, |
| 14 | + // ^ size = 2 |
| 15 | + // |
| 16 | + // Observation: Next new item will go in position size |
| 17 | + // The last item is in position size - 1 |
| 18 | + // Size is the number of items. |
| 19 | + |
| 20 | + // resize the underlying array to the desired capacity |
| 21 | + private void resize(int capacity) { |
| 22 | + Glorp[] a = (Glorp[]) new Object[capacity]; |
| 23 | + System.arraycopy(items, 0, a, 0, size); |
| 24 | + items = a; |
10 | 25 | }
|
11 | 26 |
|
12 |
| - // [3, 4, 2, 0, 0, 0, ....] |
13 |
| - // ^ (size = 3) |
14 |
| - // size is the location of the next add |
15 |
| - // size - 1 location of the last item |
16 |
| - |
17 |
| - public void addLast(int x) { |
| 27 | + public void addLast(Glorp x) { |
18 | 28 | if (size == items.length) {
|
19 | 29 | resize(size + 1);
|
20 | 30 | }
|
21 | 31 | items[size] = x;
|
22 | 32 | size += 1;
|
23 | 33 | }
|
24 | 34 |
|
25 |
| - private void resize(int newSize) { |
26 |
| - int[] a = new int[newSize + 1]; |
27 |
| - System.arraycopy(items, 0, a, 0, size); |
28 |
| - items = a; |
29 |
| - } |
30 |
| - |
31 |
| - public int getLast() { |
| 35 | + public Glorp getLast() { |
32 | 36 | return items[size - 1];
|
33 | 37 | }
|
34 | 38 |
|
35 |
| - public int get(int i) { |
| 39 | + public Glorp get(int i) { |
| 40 | + if (i >= size) { |
| 41 | + throw new IllegalArgumentException("We don't have that much stuff"); |
| 42 | + } |
36 | 43 | return items[i];
|
37 | 44 | }
|
38 | 45 |
|
39 |
| - public int removeLast() { |
40 |
| - int itemToReturn = getLast(); |
| 46 | + public Glorp removeLast() { |
| 47 | + Glorp itemToReturn = getLast(); |
41 | 48 | size -= 1;
|
42 | 49 | return itemToReturn;
|
43 | 50 | }
|
|
0 commit comments