-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArray.java
More file actions
65 lines (53 loc) · 1.47 KB
/
Array.java
File metadata and controls
65 lines (53 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
import java.util.Iterator;
import java.util.function.Supplier;
import java.util.NoSuchElementException;
public final class Array<T> implements Iterable<T>, Cloneable {
protected final Object[] data;
public Array(int length) {
data = new Object[length];
}
public Array(T...d) {
this(d.length);
for (int i = 0; i <= d.length-1;i++) {
data[i] = d[i];
}
}
public int size() {
return data.length;
}
public T get(int index) {
return (T) data[index];
}
public T getSetDefault(int index, Supplier<T> d) {
T original = get(index);
if (original == null) {
T newValue = d.get();
set(index, newValue);
return newValue;
} else {
return original;
}
}
public void set(int index, T value) {
data[index] = value;
}
public Object[] toObjectArray() {
return data.clone();
}
public Iterator<T> iterator() {
return new Iterator<T>() {
private int next = 0;
@Override
public boolean hasNext() {
return next <= size()-1;
}
@Override
public T next() {
if (next > size()-1) throw new NoSuchElementException();
T v = get(next);
next++;
return v;
}
}
}
}