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
import java.util.Iterator;
public class ArraySet<E> implements ISet<E> {
private static final int DEFAULT_CAPACITY = 10;
private static final double GROW_FACTOR = 2.0;
private E[] data;
private int size;
public ArraySet() {
this.data = (E[])new Object[DEFAULT_CAPACITY];
}
private void ensureCapacity(int size) {
if (this.capacity() < size) {
E[] newData = (E[])new Object[(int)(this.capacity()*GROW_FACTOR)];
for (int i = 0; i < this.size; i++) {
newData[i] = this.data[i];
}
this.data = newData;
}
}
private int capacity() {
return this.data.length;
}
public int size() {
return this.size;
}
@Override
public void add(E elem) {
if (!this.contains(elem)) {
this.ensureCapacity(this.size + 1);
this.data[this.size] = elem;
this.size++;
}
}
@Override
public boolean isEmpty() {
return this.size == 0;
}
@Override
public Iterator<E> iterator() {
return new ArraySetIterator();
}
/*
[1, 2, 3]
idx=0, next() => 1
idx=1
hasNext() 1 < 3 true
idx=1, next() => 2
hasNext() 2 < 3 true
*/
private class ArraySetIterator implements Iterator<E> {
private int idx;
public ArraySetIterator() {
this.idx = 0;
}
@Override
public boolean hasNext() {
return this.idx < size();
}
@Override
public E next() {
E toReturn = data[this.idx];
this.idx++;
return toReturn;
}
}
@Override
public String toString() {
if (this.isEmpty()) {
return "[]";
}
String result = "[";
for (int i = 0; i < this.size; i++) {
result += this.data[i] + ", ";
}
result = result.substring(0, result.length() - 2);
return result + "]";
}
}