-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynArr.java
More file actions
69 lines (56 loc) · 1.47 KB
/
dynArr.java
File metadata and controls
69 lines (56 loc) · 1.47 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
61
62
63
64
65
66
67
68
69
class DynamicArray {
private int[] arr;
private int length;
private int capacity;
public DynamicArray(int capacity) {
this.capacity = capacity;
this.length = 0;
this.arr = new int[this.capacity];
}
public int get(int i) {
if (i > this.length) return -1;
return this.arr[i];
}
public void set(int i, int n) {
this.arr[i] = n;
}
public void pushback(int n) {
// push to end
if (this.length == this.capacity) {
this.resize();
}
this.arr[length] = n;
this.length++;
}
public int popback() {
// decrem length by 1, return element popped back
if (this.length > 0) {
this.length --;
}
return this.arr[this.length];
}
private void resize() {
// create a new array with double the capacity
this.capacity *= 2;
int[] new_arr = new int[this.capacity];
// copy old array to new one
for (int i = 0; i < this.length; i++) {
new_arr[i] = this.arr[i];
}
this.arr = new_arr;
}
public int getSize() {
// num of elements inserted
return this.length;
}
public int getCapacity() {
return this.capacity;
}
}
/*
* https://www.youtube.com/watch?v=xT70mHdAM74
* init an array with given capacity
* save capacity, which may change
* which solves the getCapacity func; return the capacity
*
*/