-
Notifications
You must be signed in to change notification settings - Fork 82
/
UnsortedHashSet.java
46 lines (36 loc) · 1.17 KB
/
UnsortedHashSet.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
import java.util.LinkedList;
import java.lang.reflect.Array;
public class UnsortedHashSet<E> {
private static final double LOAD_FACTOR_LIMIT = 0.7;
private int size;
private LinkedList<E>[] con;
public UnsortedHashSet() {
con = (LinkedList<E>[])(new LinkedList[10]);
}
public boolean add(E obj) {
int oldSize = size;
int index = Math.abs(obj.hashCode()) % con.length;
if(con[index] == null)
con[index] = new LinkedList<E>();
if(!con[index].contains(obj)) {
con[index].add(obj);
size++;
}
if(1.0 * size / con.length > LOAD_FACTOR_LIMIT)
resize();
return oldSize != size;
}
private void resize() {
UnsortedHashSet<E> temp = new UnsortedHashSet<E>();
temp.con = (LinkedList<E>[])(new LinkedList[con.length * 2 + 1]);
for(int i = 0; i < con.length; i++){
if(con[i] != null)
for(E e : con[i])
temp.add(e);
}
con = temp.con;
}
public int size() {
return size;
}
}