-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIntList.java
More file actions
60 lines (52 loc) · 1.37 KB
/
Copy pathIntList.java
File metadata and controls
60 lines (52 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
interface IntList {
void add(int number);
int get(int id);
}
class IntArrayList implements IntList {
private int[] array;
private int size;
public IntArrayList() {
this.array = new int[10];
this.size = 0;
}
@Override
public void add(int number) {
if (size == array.length) {
int[] newArray = new int[array.length + array.length / 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
array[size++] = number;
}
@Override
public int get(int id) {
if (id < 0 || id >= size) {
throw new IndexOutOfBoundsException("Invalid index: " + id);
}
return array[id];
}
}
class IntVector implements IntList {
private int[] array;
private int size;
public IntVector() {
this.array = new int[20];
this.size = 0;
}
@Override
public void add(int number) {
if (size == array.length) {
int[] newArray = new int[array.length * 2];
System.arraycopy(array, 0, newArray, 0, array.length);
array = newArray;
}
array[size++] = number;
}
@Override
public int get(int id) {
if (id < 0 || id >= size) {
throw new IndexOutOfBoundsException("Invalid index: " + id);
}
return array[id];
}
}