-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArraySet.java
91 lines (78 loc) · 1.72 KB
/
ArraySet.java
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
public class ArraySet implements Set
{
private final static int INITIAL_CAPACITY = 1;
private Object[] v;
private int vSize;
public ArraySet()
{
makeEmpty();
}
public void makeEmpty()
{
v = new Object[INITIAL_CAPACITY];
vSize = 0;
}
public boolean isEmpty()
{
return vSize == 0;
}
public int size()
{
return vSize;
}
public boolean contains(Object x) // O(n)
{
for (int i = 0; i < vSize; i++)
if (v[i].equals(x))
return true;
return false;
}
public Object[] toArray() // O(n)
{
Object[] x = new Object[vSize];
for (int i = 0; i < vSize; i++)
x[i] = v[i]; // non si puo’ fare meglio!
return x; } // su un oggetto generico
// O(n) (usa contains)
public void add(Object x)
{
if (contains(x)) return;
if (vSize >= v.length)
v = resize(v, 2 * v.length);
v[vSize++] = x;
}
private Object[] resize(Object[] a, int length)
{…}
public static Set union(Set s1, Set s2)
{
Set x = new ArraySet();
// inseriamo gli elementi del primo insieme
Object[] v = s1.toArray();
for (int i = 0; i < v.length; i++)
x.add(v[i]);
// inseriamo tutti gli elementi del
// secondo insieme, sfruttando le
// proprietà di add (niente duplicati...)
v = s2.toArray();
for (int i = 0; i < v.length; i++)
x.add(v[i]);
return x;
}
public static Set intersection(Set s1, Set s2)
{
Set x = new ArraySet();
}
Object[] v = s1.toArray();
for (int i = 0; i < v.length; i++)
if (s2.contains(v[i]))
x.add(v[i]);
return x;
public static Set subtract(Set s1, Set s2)
{
Set x = new ArraySet();
Object[] v = s1.toArray();
for (int i = 0; i < v.length; i++)
if (!s2.contains(v[i]))
x.add(v[i]);
return x;
}