-2

What's the relation between a HashSet and a HashMap?

From javadoc:

HashSet

public HashSet()

Constructs a new, empty set; the backing HashMap instance has default initial 

capacity (16) and load factor (0.75).

And what do they mean with "load factor"? Thanks in advance.

Community
  • 1
  • 1
Rollerball
  • 12,618
  • 23
  • 92
  • 161

3 Answers3

1

HashSet is implemented in terms of HashMap:

This class implements the Set interface, backed by a hash table (actually a HashMap instance).

Load factor is explained in the documentation:

An instance of HashMap has two parameters that affect its performance: initial capacity and load factor. The capacity is the number of buckets in the hash table, and the initial capacity is simply the capacity at the time the hash table is created. The load factor is a measure of how full the hash table is allowed to get before its capacity is automatically increased. When the number of entries in the hash table exceeds the product of the load factor and the current capacity, the hash table is rehashed (that is, internal data structures are rebuilt) so that the hash table has approximately twice the number of buckets.

As a general rule, the default load factor (.75) offers a good tradeoff between time and space costs. Higher values decrease the space overhead but increase the lookup cost (reflected in most of the operations of the HashMap class, including get and put). The expected number of entries in the map and its load factor should be taken into account when setting its initial capacity, so as to minimize the number of rehash operations. If the initial capacity is greater than the maximum number of entries divided by the load factor, no rehash operations will ever occur.

Community
  • 1
  • 1
NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

What's the relation between a HashSet and a HashMap?

The relationship is that each HashSet<T> has a private HashMap<T, Object> inside it. (In the Java 7 version, values are a private Object instance ...)

And what do they mean with "load factor"?

The term "load factor" is defined in the javadoc for HashMap. You can read about it there. (That's what it was written for ...)

Reference:

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
0

From the source code of HashSet

public HashSet(Collection<? extends E> c) {
    map = new HashMap<E,Object>(Math.max((int) (c.size()/.75f) + 1, 16));
    addAll(c);
}
stinepike
  • 54,068
  • 14
  • 92
  • 112