1. Información general
En este artículo, nos sumergiremos en HashSet. Es una de las implementaciones de Set más populares , así como una parte integral de Java Collections Framework.
2. Introducción a HashSet
HashSet es una de las estructuras de datos fundamentales en la API de colecciones de Java .
Recordemos los aspectos más importantes de esta implementación:
- Almacena elementos únicos y permite nulos.
- Está respaldado por un HashMap
- No mantiene el orden de inserción
- No es seguro para subprocesos
Tenga en cuenta que este HashMap interno se inicializa cuando se crea una instancia del HashSet :
public HashSet() { map = new HashMap(); }
Si desea profundizar en cómo funciona HashMap , puede leer el artículo centrado en él aquí.
3. La API
En esta sección, revisaremos los métodos más utilizados y veremos algunos ejemplos simples.
3.1. añadir()
El método add () se puede utilizar para agregar elementos a un conjunto. El contrato de método establece que un elemento se agregará solo cuando aún no esté presente en un conjunto. Si se agregó un elemento, el método devuelve verdadero; de lo contrario, falso.
Podemos agregar un elemento a un HashSet como:
@Test public void whenAddingElement_shouldAddElement() { Set hashset = new HashSet(); assertTrue(hashset.add("String Added")); }
Desde una perspectiva de implementación, el método add es extremadamente importante. Los detalles de implementación ilustran cómo funciona el HashSet internamente y aprovecha el método put de HashMap :
public boolean add(E e) { return map.put(e, PRESENT) == null; }
La variable del mapa es una referencia al HashMap interno de respaldo :
private transient HashMap map;
Sería una buena idea familiarizarse primero con el código hash para obtener una comprensión detallada de cómo se organizan los elementos en estructuras de datos basadas en hash.
Resumiendo:
- Un HashMap es una matriz de depósitos con una capacidad predeterminada de 16 elementos; cada depósito corresponde a un valor de código hash diferente
- Si varios objetos tienen el mismo valor de código hash, se almacenan en un solo depósito
- Si se alcanza el factor de carga , se crea una nueva matriz el doble del tamaño de la anterior y todos los elementos se vuelven a procesar y se redistribuyen entre los nuevos depósitos correspondientes.
- Para recuperar un valor, aplicamos el hash a una clave, la modificamos y luego vamos al depósito correspondiente y buscamos en la lista potencial vinculada en caso de que haya más de un objeto.
3.2. contiene ()
El propósito del método contains es verificar si un elemento está presente en un HashSet dado . Devuelve verdadero si se encuentra el elemento, de lo contrario falso.
Podemos buscar un elemento en el HashSet :
@Test public void whenCheckingForElement_shouldSearchForElement() { Set hashsetContains = new HashSet(); hashsetContains.add("String Added"); assertTrue(hashsetContains.contains("String Added")); }
Siempre que se pasa un objeto a este método, se calcula el valor hash. Luego, la ubicación del depósito correspondiente se resuelve y recorre.
3.3. eliminar()
El método elimina el elemento especificado del conjunto si está presente. Este método devuelve verdadero si un conjunto contiene el elemento especificado.
Veamos un ejemplo de trabajo:
@Test public void whenRemovingElement_shouldRemoveElement() { Set removeFromHashSet = new HashSet(); removeFromHashSet.add("String Added"); assertTrue(removeFromHashSet.remove("String Added")); }
3.4. claro()
Usamos este método cuando pretendemos eliminar todos los elementos de un conjunto. La implementación subyacente simplemente borra todos los elementos del HashMap subyacente .
Veamos eso en acción:
@Test public void whenClearingHashSet_shouldClearHashSet() { Set clearHashSet = new HashSet(); clearHashSet.add("String Added"); clearHashSet.clear(); assertTrue(clearHashSet.isEmpty()); }
3.5. Talla()
This is one of the fundamental methods in the API. It's used heavily as it helps in identifying the number of elements present in the HashSet. The underlying implementation simply delegates the calculation to the HashMap's size() method.
Let's see that in action:
@Test public void whenCheckingTheSizeOfHashSet_shouldReturnThesize() { Set hashSetSize = new HashSet(); hashSetSize.add("String Added"); assertEquals(1, hashSetSize.size()); }
3.6. isEmpty()
We can use this method to figure if a given instance of a HashSet is empty or not. This method returns true if the set contains no elements:
@Test public void whenCheckingForEmptyHashSet_shouldCheckForEmpty() { Set emptyHashSet = new HashSet(); assertTrue(emptyHashSet.isEmpty()); }
3.7. iterator()
The method returns an iterator over the elements in the Set. The elements are visited in no particular order and iterators are fail-fast.
We can observe the random iteration order here:
@Test public void whenIteratingHashSet_shouldIterateHashSet() { Set hashset = new HashSet(); hashset.add("First"); hashset.add("Second"); hashset.add("Third"); Iterator itr = hashset.iterator(); while(itr.hasNext()){ System.out.println(itr.next()); } }
If the set is modified at any time after the iterator is created in any way except through the iterator's own remove method, the Iterator throws a ConcurrentModificationException.
Let's see that in action:
@Test(expected = ConcurrentModificationException.class) public void whenModifyingHashSetWhileIterating_shouldThrowException() { Set hashset = new HashSet(); hashset.add("First"); hashset.add("Second"); hashset.add("Third"); Iterator itr = hashset.iterator(); while (itr.hasNext()) { itr.next(); hashset.remove("Second"); } }
Alternatively, had we used the iterator's remove method, then we wouldn't have encountered the exception:
@Test public void whenRemovingElementUsingIterator_shouldRemoveElement() { Set hashset = new HashSet(); hashset.add("First"); hashset.add("Second"); hashset.add("Third"); Iterator itr = hashset.iterator(); while (itr.hasNext()) { String element = itr.next(); if (element.equals("Second")) itr.remove(); } assertEquals(2, hashset.size()); }
The fail-fast behavior of an iterator cannot be guaranteed as it's impossible to make any hard guarantees in the presence of unsynchronized concurrent modification.
Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it'd be wrong to write a program that depended on this exception for its correctness.
4. How HashSet Maintains Uniqueness?
When we put an object into a HashSet, it uses the object's hashcode value to determine if an element is not in the set already.
Each hash code value corresponds to a certain bucket location which can contain various elements, for which the calculated hash value is the same. But two objects with the same hashCode might not be equal.
So, objects within the same bucket will be compared using the equals() method.
5. Performance of HashSet
The performance of a HashSet is affected mainly by two parameters – its Initial Capacity and the Load Factor.
The expected time complexity of adding an element to a set is O(1) which can drop to O(n) in the worst case scenario (only one bucket present) – therefore, it's essential to maintain the right HashSet's capacity.
An important note: since JDK 8, the worst case time complexity is O(log*n).
The load factor describes what is the maximum fill level, above which, a set will need to be resized.
We can also create a HashSet with custom values for initial capacity and load factor:
Set hashset = new HashSet(); Set hashset = new HashSet(20); Set hashset = new HashSet(20, 0.5f);
In the first case, the default values are used – the initial capacity of 16 and the load factor of 0.75. In the second, we override the default capacity and in the third one, we override both.
A low initial capacity reduces space complexity but increases the frequency of rehashing which is an expensive process.
On the other hand, a high initial capacity increases the cost of iteration and the initial memory consumption.
As a rule of thumb:
- A high initial capacity is good for a large number of entries coupled with little to no iteration
- A low initial capacity is good for few entries with a lot of iteration
It's, therefore, very important to strike the correct balance between the two. Usually, the default implementation is optimized and works just fine, should we feel the need to tune these parameters to suit the requirements, we need to do judiciously.
6. Conclusion
In this article, we outlined the utility of a HashSet, its purpose as well as its underlying working. We saw how efficient it is in terms of usability given its constant time performance and ability to avoid duplicates.
We studied some of the important methods from the API, how they can help us as a developer to use a HashSet to its potential.
As always, code snippets can be found over on GitHub.