-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicBag.java
More file actions
84 lines (69 loc) · 1.59 KB
/
DynamicBag.java
File metadata and controls
84 lines (69 loc) · 1.59 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
import java.util.Iterator;
public class DynamicBag implements Bag {
private StaticBag bag;
private int maxSize;
public DynamicBag(int initialCapacity) {
this.bag = new StaticBag(initialCapacity);
this.maxSize = initialCapacity;
}
@Override
public Iterator iterator() {
return this.bag.iterator();
}
public void add(Object obj) {
if (this.bag.size() == this.maxSize) // Current bag is full
{
// Allocate a new array with 2x the capacity
this.maxSize *= 2;
StaticBag newBag = new StaticBag(this.maxSize);
// Copy existing elements into the new bag
for (Object curObj : this.bag)
newBag.add(curObj);
// Empty out old bag and replace it with the new one
this.bag.clear();
this.bag = null;
this.bag = newBag;
}
// Add the object that was sent
this.bag.add(obj);
}
public boolean erase(Object obj) {
return this.bag.erase(obj);
}
@Override
public int eraseAll(Object obj) {
return this.bag.eraseAll(obj);
}
public void clear() {
this.bag.clear();
this.maxSize = 0;
}
@Override
public int size() {
return this.bag.size();
}
@Override
public int count(Object obj) {
return this.bag.count(obj);
}
@Override
public boolean isMember(Object obj) {
return this.bag.isMember(obj);
}
@Override
public boolean isEmpty() {
return this.bag.isEmpty();
}
@Override
public Bag moreFrequentThan(Object obj) {
Bag Bag2 = new StaticBag(this.size());
for (Object object : this.bag) {
if(this.bag.count(object)> this.bag.count(obj)) {
if(Bag2.isMember(object) == false) {
Bag2.add(object);
}
}
}
return Bag2;
}
}