dir.by  
Поиск >>

Компьютер, программы
→
Java
→
Java (class, interface, collections, etc.)
 class HashMap<K,V> in Java 
посмотрели 599 раз
обновлено: 10 November 2026
HashMap contains keys and values.
You can add a key-value.
All keys are unique (you cannot add duplicate keys).
Each key is associated with only one value, i.e. we get the value from the key.
You can change the value by key.
You can delete the key-value.

When you go through all the elements in HashMap, you get the items without sorting, and not in the order that they were added to the collection.

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

HashMap
  implements interface Map<K,V> this collection contains keys and values
  Java  
interface Map<K, V>
{
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)
     {
          HashMap<String, Integer> mapNameAge = new HashMap<String, Integer>();

          // Adding elements
          mapNameAge.put("Jeck", 47);
          mapNameAge.put("Iana", 14);
          mapNameAge.put("Sveta", 42);

          // check if the key is in the collection
          Boolean hasElement = mapNameAge.containsKey("Iana");
          // hasElement = true

          // get value by key
          Integer age1 = mapNameAge.get("Iana");
          // age1 = 14

          // Option 1. Go through all the elements
          // When you go through all the elements in HashMap, you get the items without sorting, and not in the order that they were added to the collection.
          for (Map.Entry<String, Integer> elem : mapNameAge.entrySet()) {
               System.out.println(elem.getKey() + " , " + elem.getValue());
          }
          // "Jeck , 47"
          // "Sveta , 42"
          // "Iana , 14"

          // Option 2. Go through all the elements
          // When you go through all the elements in HashMap, you get the items without sorting, and not in the order that they were added to the collection.
          mapNameAge.forEach((name,age) -> {
               System.out.println(name + " , " + age);
          });
          // "Jeck , 47"
          // "Sveta , 42"
          // "Iana , 14"

          // delete element with key "Jeck"
          mapNameAge.remove("Jeck");
          // element1 = Iana, 14
          // element2 = Sveta, 42
     }
}
Documentation
  Java  
class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable
{
     static final int MAXIMUM_CAPACITY = 1 << 30;

     /* ---------------- Fields -------------- */
     transient Node<K,V>[] table;
     transient Set<Map.Entry<K,V>> entrySet;
     transient int size;
     transient int modCount;
     int threshold;
     final float loadFactor;

     /* ---------------- Constructors -------------- */
     public HashMap(int initialCapacity, float loadFactor) {
          if (initialCapacity < 0)
               throw new IllegalArgumentException("Illegal initial capacity: " +
                         initialCapacity);
          if (initialCapacity > MAXIMUM_CAPACITY)
               initialCapacity = MAXIMUM_CAPACITY;
          if (loadFactor <= 0 || Float.isNaN(loadFactor))
               throw new IllegalArgumentException("Illegal load factor: " +
                         loadFactor);
          this.loadFactor = loadFactor;
          this.threshold = tableSizeFor(initialCapacity);
     }
     public HashMap(int initialCapacity) {
          this(initialCapacity, DEFAULT_LOAD_FACTOR);
     }

     public HashMap() {
          this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
     }

     public HashMap(Map<? extends K, ? extends V> m) {
          this.loadFactor = DEFAULT_LOAD_FACTOR;
          putMapEntries(m, false);
     }

     /* ---------------- Methods -------------- */
     public int size() {
          return size;
     }

     public boolean isEmpty() {
          return size == 0;
     }

     public boolean containsKey(Object key) {
          return getNode(key) != null;
     }

     public boolean containsValue(Object value) {
          Node<K,V>[] tab; V v;
          if ((tab = table) != null && size > 0) {
               for (Node<K,V> e : tab) {
                    for (; e != null; e = e.next) {
                         if ((v = e.value) == value ||
                                   (value != null && value.equals(v)))
                              return true;
                    }
               }
          }
          return false;
     }

     public V get(Object key) {
          Node<K,V> e;
          return (e = getNode(key)) == null ? null : e.value;
     }

     public V put(K key, V value) {
          return putVal(hash(key), key, value, false, true);
     }

     public V remove(Object key) {
          Node<K,V> e;
          return (e = removeNode(hash(key), key, null, false, true)) == null ?
                    null : e.value;
     }

     public void clear() {
          Node<K,V>[] tab;
          modCount++;
          if ((tab = table) != null && size > 0) {
               size = 0;
               for (int i = 0; i < tab.length; ++i)
                    tab[i] = null;
          }
     }

     public Set<K> keySet() {
          Set<K> ks = keySet;
          if (ks == null) {
               ks = new KeySet();
               keySet = ks;
          }
          return ks;
     }

     public Collection<V> values() {
          Collection<V> vs = values;
          if (vs == null) {
               vs = new Values();
               values = vs;
          }
          return vs;
     }

     public Set<Map.Entry<K,V>> entrySet() {
          Set<Map.Entry<K,V>> es;
          return (es = entrySet) == null ? (entrySet = new EntrySet()) : es;
     }

     @Override
     public void forEach(BiConsumer<? super K, ? super V> action) {
          Node<K,V>[] tab;
          if (action == null)
               throw new NullPointerException();
          if (size > 0 && (tab = table) != null) {
               int mc = modCount;
               for (Node<K,V> e : tab) {
                    for (; e != null; e = e.next)
                         action.accept(e.key, e.value);
               }
               if (modCount != mc)
                    throw new ConcurrentModificationException();
          }
     }

     public int hashCode() {
          int h = 0;
          for (Entry<K, V> entry : entrySet())
               h += entry.hashCode();
          return h;
     }

     public boolean equals(Object o) {
          if (o == this)
               return true;

          if (!(o instanceof Map<?, ?> m))
               return false;
          if (m.size() != size())
               return false;

          try {
               for (Entry<K, V> e : entrySet()) {
                    K key = e.getKey();
                    V value = e.getValue();
                    if (value == null) {
                         if (!(m.get(key) == null && m.containsKey(key)))
                              return false;
                    } else {
                         if (!value.equals(m.get(key)))
                              return false;
                    }
               }
          } catch (ClassCastException | NullPointerException unused) {
               return false;
          }

          return true;
     }

     /* ---------------- class Node -------------- */
     static class Node<K,V> implements Map.Entry<K,V> {
          final int hash;
          final K key;
          V value;
          Node<K,V> next;

          Node(int hash, K key, V value, Node<K,V> next) {
               this.hash = hash;
               this.key = key;
               this.value = value;
               this.next = next;
          }

          public final K getKey() { return key; }
          public final V getValue() { return value; }
          public final String toString() { return key + "=" + value; }

          public final int hashCode() {
               return Objects.hashCode(key) ^ Objects.hashCode(value);
          }

          public final V setValue(V newValue) {
               V oldValue = value;
               value = newValue;
               return oldValue;
          }

          public final boolean equals(Object o) {
               if (o == this)
                    return true;

               return o instanceof Map.Entry<?, ?> e
                         && Objects.equals(key, e.getKey())
                         && Objects.equals(value, e.getValue());
          }
     }
}
 
← Previous topic
interface Map in Java
 
Next topic →
class LinkedHashMap<K,V> in Java
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

Новость "Черная пятница" Dreame в Беларуси – две недели скидок до 3400 рублей
 
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
• interface Map in Java
• class HashMap<K,V> in Java
• class LinkedHashMap<K,V> 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 ?
• You can add static functions to the interface | Java
• In the interface, using default, we create an implementation of the | this appeared in Java 8
• 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