Java Reference
In-Depth Information
6
public boolean
contains(E e);
contains
7
8
/** Add an element to the set */
9
public boolean
add(E e);
add
10
11
/** Remove the element from the set */
12
public boolean
remove(E e);
remove
13
14
/** Return true if the set doesn't contain any elements */
15
public boolean
isEmpty();
isEmpty
16
17
/** Return the number of elements in the set */
18
public int
size();
size
19 }
L
ISTING
27.5
MyHashSet.java
1
import
java.util.LinkedList;
2
3
public class
MyHashSet<E>
implements
MySet<E> {
4
class
MyHashSet
// Define the default hash-table size. Must be a power of 2
5
private static int
DEFAULT_INITIAL_CAPACITY =
4
;
default initial capacity
6
7
// Define the maximum hash-table size. 1 << 30 is same as 2^30
8
private static int
MAXIMUM_CAPACITY =
1
<<
30
;
maximum capacity
9
10
// Current hash-table capacity. Capacity is a power of 2
11
private int
capacity;
current capacity
12
13
// Define default load factor
14
private static float
DEFAULT_MAX_LOAD_FACTOR =
0.75f
;
default max load factor
15
16
// Specify a load-factor threshold used in the hash table
17
private float
loadFactorThreshold;
load-factor threshold
18
19
// The number of elements in the set
20
private int
size =
0
;
size
21
22
// Hash table is an array with each cell being a linked list
23
private
LinkedList<E>[] table;
hash table
24
25
/** Construct a set with the default capacity and load factor */
26
public
MyHashSet() {
no-arg constructor
27
this
(DEFAULT_INITIAL_CAPACITY, DEFAULT_MAX_LOAD_FACTOR);
28 }
29
30
/** Construct a set with the specified initial capacity and
31
* default load factor */
32
public
MyHashSet(
int
initialCapacity) {
constructor
33
this
(initialCapacity, DEFAULT_MAX_LOAD_FACTOR);
34 }
35
36
/** Construct a set with the specified initial capacity
37
* and load factor */
38
public
MyHashSet(
int
initialCapacity,
float
loadFactorThreshold) {
constructor
39
if
(initialCapacity > MAXIMUM_CAPACITY)
40
this
.capacity = MAXIMUM_CAPACITY;
41
else
42
this
.capacity = trimToPowerOf2(initialCapacity);
Search WWH ::
Custom Search