-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayUtil.java
More file actions
69 lines (57 loc) · 1.42 KB
/
ArrayUtil.java
File metadata and controls
69 lines (57 loc) · 1.42 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
import java.util.function.Predicate;
public class ArrayUtil {
/**
* "pops" the last element of the array off.
*
* @return the element.
*/
public static <T> T pop(T[] array) {
int length = array.length;
if (length == 0 || array == null)
return null;
T temp = array[length];
array[length] = null;
return temp;
}
/**
* Takes an array, and ...arguments, and <b>push</b>es the elements inside the array
*
* @return the new length of the array
*/
public static <T> int push(T[] array, T... elements) {
array = (T[]) Lists.newArrayList(array, elements).toArray(); // i really feel like i cheated on this one.
return array.length;
}
/**
*
* @param <T>
* @param array
* @param element
* @return the index of the element inside the array, returns -1 if it doesn't exist.
*/
public static <T> int indexOf(T[] array, T element) {
return findIndex(array, r -> r == element);
}
/**
*
* @param <T>
* @param array
* @param predicate the function to be called on the array
* @return the index of the <b>first</b> found test of the predicate to return to true.
* <br>
* <code>
* int index = findIndex(new Integer[] { 1, 2, 3, 4, 5, 6}, val -> val <= 2);
* </code>
* <br>
* PRIMITIVE TYPES ARE NOT ALLOWED!
*/
public static <T> int findIndex(T[] array, Predicate predicate) {
int k = -1;
for (T t: array) {
k++;
if (predicate.test(t))
break;
}
return k;
}
}