Repository navigation
Expand file tree
/
Copy pathMySet.java
More file actions
114 lines (80 loc) · 2.23 KB
/
Copy pathMySet.java
File metadata and controls
114 lines (80 loc) · 2.23 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
import java.util.*;
public class MySet {
private static final int INITIAL_SIZE = 7;
private List<Integer>[] table;
private int size;
public MySet() {
table = createTable(INITIAL_SIZE);
size = 0;
}
List<Integer>[] createTable(int size) {
List<Integer>[] result = new List[size];
for(int i = 0; i < result.length; i++) {
result[i] = new ArrayList<Integer>();
}
return result;
}
public boolean add(int value) {
int entry = value % table.length;
if(!table[entry].contains(value)) {
table[entry].add(value);
size++;
resizeIfNecessary();
return true;
}
return false;
}
public boolean remove(int value) {
int entry = value % table.length;
if(!table[entry].contains(value)) {
return false;
}
table[entry].remove((Integer) value);
size--;
resizeIfNecessary();
return true;
}
public boolean contains(int value) {
int entry = value % table.length;
return table[entry].contains(value);
}
private void resizeIfNecessary() {
if(size > (0.75 * table.length)) {
//System.out.println("Doubling size");
// Save old table
// Reinitialize the hash table (twice the size)
// Add all elements from the old table into the new table
}
}
public int size() {
return size;
}
public static void main(String[] args) {
MySet set = new MySet();
System.out.println("Contains 7? " + set.contains(7));
set.add(7);
System.out.println("Contains 7? " + set.contains(7));
System.out.println("Size: " + set.size());
System.out.println("Contains 9? " + set.contains(9));
set.add(9);
System.out.println("Contains 9? " + set.contains(9));
System.out.println("Size: " + set.size());
System.out.println("Contains 14? " + set.contains(14));
set.add(14);
System.out.println("Contains 14? " + set.contains(14));
System.out.println("Size: " + set.size());
set.remove(7);
System.out.println("Contains 7? " + set.contains(7));
System.out.println("Contains 14? " + set.contains(14));
System.out.println("Size: " + set.size());
for(int i = 0; i < 1000; i++) {
set.add(i * i);
}
System.out.println("Size: " + set.size());
for(int i = 0; i < 1000; i++) {
if(!set.contains(i * i)) {
System.err.println("Ooops! Does not contain " + (i * i));
}
}
}
}