In Java basics, HashMap is a commonly used collection class. It stores data in the form of key-value pairs and can quickly access and find data. The remove() method is used to delete the specified key-value pair. This article will analyze its usage in detail and attach specific code examples.
The remove() method of the HashMap class has two overloaded forms:
public V remove(Object key)
public boolean remove(Object key, Object value)
Among them, the first The method is used to delete the key-value pair corresponding to the specified key and return the value corresponding to the key; the second method is to delete the key-value pair and only if the specified key and the specified value match. Returns true, otherwise returns false.
In the following code example, we will create a HashMap object and add key-value pairs to it. Then delete the specified key-value pair through the remove() method, and output the deleted HashMap content.
import java.util.HashMap; public class HashMapDemo { public static void main(String[] args) { // 创建HashMap对象 HashMap<String, String> hashMap = new HashMap<>(); // 向HashMap中添加键值对 hashMap.put("1", "One"); hashMap.put("2", "Two"); hashMap.put("3", "Three"); hashMap.put("4", "Four"); // 删除键为3的键值对 String removedValue = hashMap.remove("3"); System.out.println("删除的键值对为:" + "3" + " => " + removedValue); // 删除键为2,值为"Three"的键值对 boolean isRemoved = hashMap.remove("2", "Three"); System.out.println("删除的键值对是否存在:" + isRemoved); // 输出删除后的HashMap内容 System.out.println("删除后的HashMap内容为:"); hashMap.forEach((key, value) -> System.out.println(key + " => " + value)); } }
The running results are as follows:
删除的键值对为:3 => Three 删除的键值对是否存在:false 删除后的HashMap内容为: 4 => Four 1 => One
When using the remove() method to delete the key-value pairs in the HashMap When doing so, you need to pay attention to the following points:
In short, after understanding the usage and precautions of the remove() method, you can operate HashMap collections more flexibly and improve program efficiency.
The above is the detailed content of Java documentation interpretation: Detailed explanation of the use of the remove() method of the HashMap class. For more information, please follow other related articles on the PHP Chinese website!