dir.by  
Поиск >>

Компьютер, программы
→
Java
→
Java (class, interface, collections, etc.)
 class HashSet in Java 
посмотрели 1176 раз
обновлено: 9 October 2026
HashSet contains a non-repeating collection of items.
HashSet contains unsorted items.
HashSet allows you to quickly determine whether such an element exists or not (fast because it uses an index that is calculated from the hash code of the element).
HashSet has methods Add, Remove, Contains and uses a hash implementation, so these methods take 1 action (the Contains and Remove methods in ArrayList take n actions.)

HashSet is not synchronized. If multiple threads access a hash set concurrently, and at least one of the threads modifies the HashSet, it must be synchronized externally.

HashSet
  implements interface Set<E> is a collection of unique elements
  Java  
interface Set<E> extends Collection<E>
{
Let's look at Functions >> ...
}
Example
  Java     Creating a new Java console application ... and write the code
package org.example;
import java.util.Stack;

public class Program {
     public static void main(String[] args)
     {
          HashSet<String> myHashSet1 = new HashSet<String>();

          // Adding elements
          myHashSet1.add("Car");
          myHashSet1.add("House");
          myHashSet1.add("Book");

          // Check if the item is in the collection
          Boolean hasElement = myHashSet1.contains("House");
          // hasElement = true

          // Go through all the elements
          for(String str:myHashSet1)
          {
               System.out.println(str);
          }
          // element1 = Car
          // element2 = Book
          // element3 = House

          // delete the element "Book"
          myHashSet1.remove("Book");
          // element1 = Car
          // element3 = House

     }
}
Как устроен HashSet
class HashSet<E> inside contains HashMap:
  Java  
class HashSet<E>
{
     HashMap<E,Object> map;

     ...
     // In all public constructors, HashMap is created
     public HashSet(...) {
          map = new HashMap<>(...);
     }

}


Documentation
  Java  
class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, java.io.Serializable
{
     HashMap<E,Object> map;

     public HashSet() {
          map = new HashMap<>();
     }

     public HashSet(Collection<? extends E> c) {
          map = HashMap.newHashMap(Math.max(c.size(), 12));
          addAll(c);
     }

     public HashSet(int initialCapacity, float loadFactor) {
          map = new HashMap<>(initialCapacity, loadFactor);
     }

     public HashSet(int initialCapacity) {
          map = new HashMap<>(initialCapacity);
     }

     private HashSet(int initialCapacity, float loadFactor, boolean dummy) {
          map = new LinkedHashMap<>(initialCapacity, loadFactor);
     }

     public Iterator<E> iterator() {
          return map.keySet().iterator();
     }

     public int size() {
          return map.size();
     }

     public boolean isEmpty() {
          return map.isEmpty();
     }

     public boolean contains(Object o) {
          return map.containsKey(o);
     }

     public boolean add(E e) {
          return map.put(e, PRESENT)==null;
     }

     public boolean remove(Object o) {
          return map.remove(o)==PRESENT;
     }

     public void clear() {
          map.clear();
     }

     public Object clone() {
          try {
               HashSet<E> newSet = (HashSet<E>) super.clone();
               newSet.map = (HashMap<E, Object>) map.clone();
               return newSet;
          } catch (CloneNotSupportedException e) {
               throw new InternalError(e);
          }
     }

     @java.io.Serial
     private void writeObject(java.io.ObjectOutputStream s)
               throws java.io.IOException {
               ...
     }

     @java.io.Serial
     private void readObject(java.io.ObjectInputStream s)
               throws java.io.IOException, ClassNotFoundException {
               ...
     }

     public Spliterator<E> spliterator() {
          return new HashMap.KeySpliterator<>(map, 0, -1, 0, 0);
     }

     @Override
     public Object[] toArray() {
          return map.keysToArray(new Object[map.size()]);
     }

     @Override
     public <T> T[] toArray(T[] a) {
          return map.keysToArray(map.prepareArray(a));
     }

     public static <T> HashSet<T> newHashSet(int numElements) {
          if (numElements < 0) {
               throw new IllegalArgumentException("Negative number of elements: " + numElements);
          }
          return new HashSet<>(HashMap.calculateHashMapCapacity(numElements));
     }

}
Learn more about methods in the Java documentation: https://docs.oracle.com ...
 
← Previous topic
interface Set in Java
 
Next topic →
class LinkedHashSet<E> in Java
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

 
Download and install
• Installation JDK (download and install the Java library for Windows)
• Download and install IntelliJ IDEA to explore Java, Spring, Jakarta EE | Functionality and differences: Community | Ultimate
• Error "JDK is missing" | Java
Java (class, interface, collections, etc.)
• Create a simple console app in IntelliJ IDEA to learn Java
• Access modifiers (private, protected, public) for a class and for methods and fields. | Java
• Collections in Java
• interface List<E> in Java
• class ArrayList<E> in Java
• class Vector<E> in Java
• class Stack<E> in Java
• class CopyOnWriteArrayList<E> in Java
• interface Queue<E> in Java
• interface Deque<E> in Java
• class LinkedList<E> in Java
• interface Set in Java
• class HashSet<E> in Java
• class LinkedHashSet<E> in Java
• Collections.singletonList("Hello") returns an immutable list containing exactly one specified element | Java collection
• class Collections (all functions, algorithms) | Java
• stream.filter(...) select elements according to your criterion | Java collection | Example: allCars.stream().filter(item -> item.Price < 30000).toList()
• What is interface in Java ?
• Directly in the code (at runtime) we make an implementation for the interface | Java
• Threads in Java
• lambda is an unnamed method (no name and no class owned) | Java
• Exceptions and handling in Java. Example: try {...} catch (Exception e) {...}
• Why use throws Exception in the function name in Java? Answer: The method throws an exception and there is no handling of try catch. Example: float CalculateDensity(float mass, float volume) throws Exception { ... throw new Exception("Error! Volume is zero."); ... }
Java web application (servlet, jsp page, basic functionality and no frameworks)
• Creating a new simple web application (jsp web page) | Java, Maven
• Create a web servlet (the servlet is located on the web server, returns the result on request) | Java
• Installation Tomcat web server (download and install for Windows)
• Check, test Tomcat web server (create a new my.hml file)
• What is Maven
• What is a dynamic web page jsp (Java Server Page) ?
• How to install Smart Tomcat plugin in Intellij Idea
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java
Spring in Java (Spring Framework, Spring Data, Spring Boot, ...)
• What is Spring? Why use Spring in Java?
• What is Spring Bean? What is Spring Container? IoC (inversion of control) | Creating a simple Spring project and configuration Spring Container in an XML file | Editor IntelliJ Idea and language Java
• What is Dependency Injection in Spring? Creating a simple Spring project with Dependency Injection in the constructor with the attributes @Component, @Autowired | Editor IntelliJ Idea and language Java
• Create a new Spring Web application (the request goes to the Controller → Controller creates a response as text or json) | Java, Spring Web, Spring Boot, Maven
• Creating a new Spring WebSocket application (Java WebSocket sends a message to the JavaScript WebSocket) | Java, Spring WebSocket, Spring Boot, Maven
• Create Azure Web App with the type Java (free). That is, create an empty web server
• Put the Java Spring web application in Azure
• Connect to the application Azure Web App (Java) via FTP | use File Explorer
• Error "The SDK is not specified for module ... | Project SDK is not defined ..." in IntelliJ IDEA | Java, Spring Boot
• How to install Spring WebSocket plugin in Intellij Idea
Jakarta EE / Java EE in Java (Web Applications, Web Services)
• What is Jakarta EE (Java EE)? | In which editor (program) is it convenient to write Jakarta EE (Java EE) code?
• Creating a simple web project in IntelliJ Idea Ultimate | Jakarta EE (Java EE)
Struts in Java (extends API Java Servlet using MVC)
• What is Struts | Java
Courses, training
• Course "Java developer" from Yandex
Interview
• Interviews on Java

  Ваши вопросы присылайте по почте: info@dir.by