-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStaticBag.java
More file actions
115 lines (93 loc) · 2.2 KB
/
StaticBag.java
File metadata and controls
115 lines (93 loc) · 2.2 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
105
106
107
108
109
110
111
112
113
114
115
import java.util.Iterator;
import java.util.NoSuchElementException;
public class StaticBag implements Bag {
// elements to be stored in the bag
public Object[] elements;
// current size
private int currentSize;
private class BagIterator implements Iterator {
private int currentPosition;
@Override
public boolean hasNext() {
return this.currentPosition < size();
}
@Override
public Object next() {
if (this.hasNext()) {
Object result = elements[this.currentPosition++];
return result;
}
else
throw new NoSuchElementException();
}
}
public StaticBag(int maxSize) {
if (maxSize < 1)
throw new IllegalArgumentException("Bag size must be at least 1");
this.elements = new Object[maxSize];
this.currentSize = 0;
}
public void add(Object obj) {
if (this.size() == this.elements.length)
throw new IllegalStateException("Trying to insert into a full Bag.");
else
// enough space
this.elements[this.currentSize++] = obj;
}
public boolean erase(Object obj) {
for (int i = 0; i < this.size(); i++)
{
if (elements[i].equals(obj)) // Found it
{
elements[i] = elements[--this.currentSize];
elements[this.currentSize] = null; // avoid memory leak
return true;
}
}
// If we're still here, we didn't find the element
return false;
}
public int eraseAll(Object obj) {
int result = 0;
while (this.erase(obj))
++result;
return result;
}
public void clear() {
for (int i = 0; i < this.size(); i++)
this.elements[i] = null;
this.currentSize = 0;
}
public int size() {
return this.currentSize;
}
public int count(Object obj) {
int counter = 0;
for (int i = 0; i < this.size(); i++)
{
if (this.elements[i].equals(obj))
counter++;
}
return counter;
}
public boolean isMember(Object obj) {
return this.count(obj) > 0;
}
public boolean isEmpty() {
return this.size() == 0;
}
public Iterator iterator() {
return new BagIterator();
}
public Bag moreFrequentThan(Object obj) {
Bag Bag2 = new StaticBag(currentSize);
for (Object object : this) {
if(this.count(object)> this.count(obj)) {
if(Bag2.isMember(object) == false) {
Bag2.add(object);
}
}
}
return Bag2;
}
}