forked from PacktPublishing/Java-Coding-Problems
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathResizableArray.java
More file actions
104 lines (73 loc) · 2.82 KB
/
Copy pathResizableArray.java
File metadata and controls
104 lines (73 loc) · 2.82 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package modern.challenge;
import java.util.Arrays;
public final class ResizableArray {
private ResizableArray() {
throw new AssertionError("Cannot be instantiated");
}
public static int[] add(int[] arr, int item) {
if (arr == null) {
throw new IllegalArgumentException("The given array cannot be null");
}
int[] newArr = Arrays.copyOf(arr, arr.length + 1);
newArr[newArr.length - 1] = item;
// or, using System.arraycopy()
// int[] newArr = new int[arr.length + 1];
// System.arraycopy(arr, 0, newArr, 0, arr.length);
// newArr[newArr.length - 1] = item;
return newArr;
}
public static int[] remove(int[] arr) {
if (arr == null) {
throw new IllegalArgumentException("The given array cannot be null");
}
if (arr.length < 1) {
throw new IllegalArgumentException("The given array length must be greater than 0");
}
int[] newArr = Arrays.copyOf(arr, arr.length - 1);
// or, using System.arraycopy()
// int[] newArr = new int[arr.length - 1];
// System.arraycopy(arr, 0, newArr, 0, arr.length - 1);
return newArr;
}
public static int[] resize(int[] arr, int length) {
if (arr == null) {
throw new IllegalArgumentException("The given array cannot be null");
}
if (length < 0) {
throw new IllegalArgumentException("The given length cannot be smaller than 0");
}
int[] newArr = Arrays.copyOf(arr, arr.length + length);
// or, using System.arraycopy()
// int[] newArr = new int[arr.length + length];
// System.arraycopy(arr, 0, newArr, 0, arr.length);
return newArr;
}
public static <T> T[] addObject(T[] arr, T item) {
if (arr == null) {
throw new IllegalArgumentException("The given array cannot be null");
}
if (item == null) {
throw new IllegalArgumentException("The given item cannot be null");
}
T[] newArr = Arrays.copyOf(arr, arr.length + 1);
newArr[newArr.length - 1] = item;
return newArr;
}
public static <T> T[] removeObject(T[] arr) {
if (arr == null) {
throw new IllegalArgumentException("The given array cannot be null");
}
T[] newArr = Arrays.copyOf(arr, arr.length - 1);
return newArr;
}
public static <T> T[] resize(T[] arr, int length) {
if (arr == null) {
throw new IllegalArgumentException("The given array cannot be null");
}
if (length < 0) {
throw new IllegalArgumentException("The given length cannot be smaller than 0");
}
T[] newArr = Arrays.copyOf(arr, arr.length + length);
return newArr;
}
}