目录

HashMap在java中的应用及示例

HashMap自1.2起就是java集合的一部分,它提供了java基本的map映射接口实现。通过将数据储存在(Key, Value)也就是键值对中。想要得到值就必须知道对应的键。之所以用 HashMap 命名是因为它使用了一个叫做 Hashing 的技术,Hashing 是一种可以将长字符串转换成短字符串并且表示的字符串相同。段字符串的好处是更快的标记和索引。HashSet同样偶尔使用HashMap,偶尔也会使用链表来储存键值对。

几个HashMap的重要属性:

  • HashMap是java.util包的一部分
  • HashMap集成子抽象类AbstractMap,并且AbstractMap也提供一个不万丈的Map接口实现。
  • 它同样实现了可克隆和可序列化接口,K和V在之前的描述中分别代表Key和Value
  • HashMap不允许有重复的Keys但是允许有重复的Values,即一个单独的key不能包含多个value,但不止一个key可以包含一个同样的value。
  • HashMap允许唯一空Key但允许多个空Values
  • 这个类不保证映射的顺序,它不能保证顺序一直保持不变,它和HashTable大致相似,但是不同步。

HashMap的内部结构

HashMap的内在包含了一个节点数组,其中一个节点可以表示成一个包含四个领域的类。

  1. int hash
  2. K key
  3. V value
  4. Node<K,V> next

Node包含了它自身对象的引用,所以这是一个链表。

HashMap:

HashMap的性能

  1. 初始容量(Initial Capacity)
  2. 负荷系数(Load Factor)
    • \(负荷系数 = \cfrac{表中存储的元素的数量}{哈希表的大小}\)
    • 示例:如果内部容量为16,负载系数为0.75,那么当表中有12个元素时,bucket的数量将自动增加。

容量即容器的承载量,一旦HashMap被实例化即有了初始容量负荷系数使用来测量何时重新散列需要停止。重新散列是用来提升容量的步骤。在HashMap中容量是乘以2。负荷系数同样是测量那些部分在重新散列之前允许被填入。当HashMap中的条目数增加了当前容量和负载因子的乘积时,就会增加容量,这时就进行了重新散列。如果初始容量持续增高那么重新散列用不会停止,但是通过不断的增高初始容量它增加了迭代的时间复杂度,所以他应该谨慎选择来提升他的性能,当设置初始容量时应该将预计的values考虑在内。通常情况下负荷系数设置为0.75,它较好地平衡了时间和空间花费。负荷系数的value在0-1之间

同步HashMap

HashMap是非同步的也就是说多线程可以同时访问。如果多线程同是访问这个类而且至少有一个线程改变他的结构那么就有必要让他在外部同步。它是通过同步一些封装了映射的对象来完成的。如果不存在这样的对象,则可以将其封装在Collections.synchronizedMap()中,以使HashMap同步,并避免意外的非同步访问。

示例如下:

  1. Map m = Collections.synchronizedMap(new HashMap(...));Map

现在Map m是同步的了

如果在创建迭代器之后进行任何结构修改(除了通过迭代器的remove方法之外的任何方式),该类的迭代器都是快速失效的。在迭代器失败时,它将抛出ConcurrentModificationException。

HashMap的构造函数

HashMap提供了4个构造函数,每个的访问修饰符都是公共的:

  1. HashMap():它是创建HashMap实例的默认构造函数,初始容量为16,负载系数为0.75。
  2. HashMap(int初始容量):它创建一个HashMap实例,该实例具有指定的初始容量和负载因子0.75。
  3. HashMap(int初始容量,float loadFactor):它创建一个HashMap实例,该实例具有指定的初始容量和指定的负载因子。
  4. HashMap(Map Map):它使用与指定映射相同的映射创建HashMap实例。

Example:

  1. // Java program to illustrate
  2. // Java.util.HashMap
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class GFG {
  6. public static void main(String[] args)
  7. {
  8. HashMap<String, Integer> map
  9. = new HashMap<>();
  10. print(map);
  11. map.put("vishal", 10);
  12. map.put("sachin", 30);
  13. map.put("vaibhav", 20);
  14. System.out.println("Size of map is:-"+ map.size());
  15. print(map);
  16. if (map.containsKey("vishal")) {
  17. Integer a = map.get("vishal");
  18. System.out.println("value for key"+ " \"vishal\" is:- "+ a);
  19. }
  20. map.clear();
  21. print(map);
  22. }
  23. public static void print(Map<String, Integer> map)
  24. {
  25. if (map.isEmpty()) {
  26. System.out.println("map is empty");
  27. }
  28. else {
  29. System.out.println(map);
  30. }
  31. }
  32. }

输出:

  1. map is empty
  2. Size of map is:- 3
  3. {vaibhav=20, vishal=10, sachin=30}
  4. value for key "vishal" is:- 10
  5. map is empty

HashMap的时间复杂度

HashMap为基本操作提供了恒定的时间复杂度,如果正确编写了散列函数,并且正确地将元素分散到各个buckets中,则使用get和put。遍历所有的HashMap取决于HashMap的容量和许多键-值对。通常来说,它与容量+大小成正比。容量是HashMap中的buckets。所以一开始在HashMap中保留大量bucket不友好。

HashMap的方法

1. void clear():用于从映射中删除所有映射。

  • 语法 Hash_Map.clear()
  • 参数:无参数
  • 返回值: 无返回值
  • 示例如下:
  1. //将字符串映射成为整数键
  2. // Java code to illustrate the clear() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Clearing the hash map using clear()
  18. hash_map.clear();
  19. // Displaying the final HashMap
  20. System.out.println("Finally the maps look like this: " + hash_map);
  21. }
  22. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. Finally the maps look like this: {}
  1. //将整数映射成为字符串
  2. // Java code to illustrate the clear() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Clearing the hash map using clear()
  18. hash_map.clear();
  19. // Displaying the final HashMap
  20. System.out.println("Finally the maps look like this: " + hash_map);
  21. }
  22. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. Finally the maps look like this: {}

2. boolean containsKey(key_element)查询是否存在指定键的映射

  • 语法 Hash_Map.containsKey(key_element)
  • 参数: 只有key_element参数指向在映射中想要查询的映射元素。
  • 返回值:返回值只有ture和false
  • 示例如下:
  1. //将字符串映射为整数
  2. // Java code to illustrate the containsKey() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Checking for the key_element '20'
  18. System.out.println("Is the key '20' present? " +
  19. hash_map.containsKey(20));
  20. // Checking for the key_element '5'
  21. System.out.println("Is the key '5' present? " +
  22. hash_map.containsKey(5));
  23. }
  24. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. Is the key '20' present? true
  3. Is the key '5' present? false
  1. //将整数映射成为字符串
  2. // Java code to illustrate the containsKey() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Checking for the key_element 'Welcomes'
  18. System.out.println("Is the key 'Welcomes' present? " +
  19. hash_map.containsKey("Welcomes"));
  20. // Checking for the key_element 'World'
  21. System.out.println("Is the key 'World' present? " +
  22. hash_map.containsKey("World"));
  23. }
  24. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. Is the key 'Welcomes' present? true
  3. Is the key 'World' present? false

3. boolean containsValue(Object value):用于删除映射中任何特定键的值

  • 语法:Hash_Map.containsValue(Object Value)
  • 参数: 该方法仅接受对象类型的一个参数值,并引用其映射应该由映射内的任何键进行检查的值。
  • 返回值:如果检测到值的映射,则该方法返回布尔值true,其余情况均为false。
  • 时间复杂度:O(n)
  • 示例如下:
  1. // 将字符串映射为整数
  2. // Java code to illustrate the containsValue() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Checking for the Value 'pomelos'
  18. System.out.println("Is the value 'pomelos' present? " +
  19. hash_map.containsValue("pomelos"));
  20. // Checking for the Value 'World'
  21. System.out.println("Is the value 'World' present? " +
  22. hash_map.containsValue("World"));
  23. }
  24. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. Is the value 'pomelos' present? true
  3. Is the value 'World' present? false
  1. // 经整数映射为字符串
  2. // Java code to illustrate the containsValue() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Checking for the Value '10'
  18. System.out.println("Is the value '10' present? " +
  19. hash_map.containsValue(10));
  20. // Checking for the Value '30'
  21. System.out.println("Is the value '30' present? " +
  22. hash_map.containsValue(30));
  23. // Checking for the Value '40'
  24. System.out.println("Is the value '40' present? " +
  25. hash_map.containsValue(40));
  26. }
  27. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. Is the value '10' present? false
  3. Is the value '30' present? true
  4. Is the value '40' present? false

4. Object clone():它用于返回上述散列映射的浅拷贝

  • 语法 Hash_Map.clone()
  • 参数: 无参数
  • 返回值:该方法只返回HashMap的一个副本
  • 示例如下:
  1. // 将字符串映射为数字
  2. // Java code to illustrate the clone() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Displaying the cloned HashMap using clone()
  18. System.out.println("The cloned map look like this: " + hash_map.clone());
  19. }
  20. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The cloned map look like this: {25=Welcomes, 10=pomelos, 20=pomelos, 30=You, 15=4}
  1. // 将整数映射为字符串
  2. // Java code to illustrate the clone() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Displaying the cloned HashMap using clone()
  18. System.out.println("The cloned map look like this: " + hash_map.clone());
  19. }
  20. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The cloned map look like this: {pomelos=20, 4=15, You=30, Welcomes=25}

5. boolean isEmpty():用于返回散列映射的集合视图

  • 语法 Hash_Map.isEmpty()
  • 参数: 无参数
  • 返回值: 如果映射为空或不包含任何映射对,则该方法返回布尔值true,反之则为false。
  • 示例如下:
  1. // 将整数映射成为字符串
  2. // Java code to illustrate the isEmpty() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("The Mappings are: " + hash_map);
  17. // Checking for the emptiness of Map
  18. System.out.println("Is the map empty? " + hash_map.isEmpty());
  19. }
  20. }

输出:

  1. The Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. Is the map empty? false
  1. // 对于空hashMap
  2. // Java code to illustrate the isEmpty() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Displaying the HashMap
  10. System.out.println("The Mappings are: " + hash_map);
  11. // Checking for the emptiness of Map
  12. System.out.println("Is the map empty? " + hash_map.isEmpty());
  13. }
  14. }

输出:

  1. The Mappings are: {}
  2. Is the map empty? true

6. Set entrySet():用于返回散列映射的Set视图

  • 语法 hash_map.entrySet()
  • 参数:无参数
  • 返回值: 该方法返回与散列映射具有相同元素的集合。
  • 示例:
  1. // 字符串映射成整数
  2. // Java code to illustrate the entrySet() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using entrySet() to get the set view
  18. System.out.println("The set is: " + hash_map.entrySet());
  19. }
  20. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The set is: [20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4]
  1. // 讲整数映射成为字符串
  2. // Java code to illustrate the entrySet() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using entrySet() to get the set view
  18. System.out.println("The set is: " + hash_map.entrySet());
  19. }
  20. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The set is: [4=15, pomelos=20, You=30, Welcomes=25]

7. Object get(Object key):用于检索或获取由特定键映射的值

  • 语法 hash_map.keySet()
  • 参数: 无需参数
  • 返回值: 该方法返回一个具有散列映射键的集合。
  • 示例如下:
  1. // 将字符串映射为整数值
  2. // Java code to illustrate the keySet() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using keySet() to get the set view of keys
  18. System.out.println("The set is: " + hash_map.keySet());
  19. }
  20. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The set is: [20, 25, 10, 30, 15]
  1. // 将整数映射成为字符串
  2. // Java code to illustrate the keySet() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using keySet() to get the set view of keys
  18. System.out.println("The set is: " + hash_map.keySet());
  19. }
  20. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The set is: [4, pomelos, You, Welcomes]

8. Set ketSet():它用于返回键的集合视图

  1. * 语法 hash_map.keySet()
  2. * 参数: 无参数
  3. * 返回值:该方法返回一个具有散列映射键的集合。
  4. * 示例如下:
  1. // 将字符串映射为整数
  2. // Java code to illustrate the keySet() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using keySet() to get the set view of keys
  18. System.out.println("The set is: " + hash_map.keySet());
  19. }
  20. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The set is: [20, 25, 10, 30, 15]
  1. //将整数映射为字符串
  2. // Java code to illustrate the keySet() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using keySet() to get the set view of keys
  18. System.out.println("The set is: " + hash_map.keySet());
  19. }
  20. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The set is: [4, pomelos, You, Welcomes]

9. int size():它用于返回映射的大小

  1. * 语法: Hash_Map.size()
  2. * 参数: 无需参数
  3. * 返回值: 该方法返回映射的大小,这也表示映射中存在的键值对的数量。
  4. * 示例如下
  1. //将字符串映射成为整数
  2. // Java code to illustrate the size() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Displaying the size of the map
  18. System.out.println("The size of the map is " + hash_map.size());
  19. }
  20. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The size of the map is 5
  1. // 将整数映射成为字符串
  2. // Java code to illustrate the size() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Displaying the size of the map
  18. System.out.println("The size of the map is " + hash_map.size());
  19. }
  20. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The size of the map is 4

10. Object put(Object key,Object value):用于将键值对的特定映射插入到映射中。

  • 语法 Hash_Map.put(key, value)
  • 参数: 该方法有两个参数,都是HashMap的对象类型。
    • key: This refers to the key element that needs to be inserted into the Map for mapping.
    • value: This refers to the value that the above key would map into.
  • 返回值: 如果传递了现有的键,则返回以前的值。如果传递了一个新对,则返回NULL。
  • 示例如下:
  1. // 当传递一个存在key
  2. // Java code to illustrate the put() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Inserting existing key along with new value
  18. String returned_value = (String)hash_map.put(20, "All");
  19. // Verifying the returned value
  20. System.out.println("Returned value is: " + returned_value);
  21. // Displayin the new map
  22. System.out.println("New map is: " + hash_map);
  23. }
  24. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. Returned value is: pomelos
  3. New map is: {20=All, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  1. // 当传递一个新值
  2. // Java code to illustrate the put() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Inserting existing key along with new value
  18. String returned_value = (String)hash_map.put(50, "All");
  19. // Verifying the returned value
  20. System.out.println("Returned value is: " + returned_value);
  21. // Displayin the new map
  22. System.out.println("New map is: " + hash_map);
  23. }
  24. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. Returned value is: null
  3. New map is: {50=All, 20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}

11. putAll(Map M):它用于将一个映射中的所有元素复制到另一个映射中。

  • 语法 new_hash_map.putAll(exist_hash_map)
  • 参数:该方法接受一个参数exist_hash_map,该参数引用我们想要复制的现有映射。
  • 返回值: 无返回值
  • 异常:如果我们想要复制的映射是NULL,这个方法会抛出 NullPointerException。
  • 示例如下:
  1. // 将字符串映射为整数
  2. // Java code to illustrate the putAll() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args) {
  6. // Creating an empty HashMap
  7. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  8. // Mapping string values to int keys
  9. hash_map.put(10, "pomelos");
  10. hash_map.put(15, "4");
  11. hash_map.put(20, "pomelos");
  12. hash_map.put(25, "Welcomes");
  13. hash_map.put(30, "You");
  14. // Displaying the HashMap
  15. System.out.println("Initial Mappings are: " + hash_map);
  16. // Creating a new hash map and copying
  17. HashMap<Integer, String> new_hash_map = new HashMap<Integer, String>();
  18. new_hash_map.putAll(hash_map);
  19. // Displaying the final HashMap
  20. System.out.println("The new map looks like this: " + new_hash_map);
  21. }
  22. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The new map looks like this: {25=Welcomes, 10=pomelos, 20=pomelos, 30=You, 15=4}
  1. // 将整数映射成为字符串
  2. // Java code to illustrate the putAll() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Creating a new hash map and copying
  18. HashMap<String, Integer> new_hash_map = new HashMap<String, Integer>();
  19. new_hash_map.putAll(hash_map);
  20. // Displaying the final HashMap
  21. System.out.println("The new map looks like this: " + new_hash_map);
  22. }
  23. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The new map looks like this: {pomelos=20, 4=15, You=30, Welcomes=25}

12. Object remove(Object key):它用于删除映射中任何特定键的值。

  • 语法 Hash_Map.remove(Object key)
  • 参数: 该方法采用一个要从映射中删除其映射的参数键。
  • 返回值:如果键存在,该方法将返回先前映射到指定键的值,否则将返回NULL。
  • 示例如下:
  1. // 当传递一个已存在key
  2. // Java code to illustrate the remove() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args) {
  6. // Creating an empty HashMap
  7. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  8. // Mapping string values to int keys
  9. hash_map.put(10, "pomelos");
  10. hash_map.put(15, "4");
  11. hash_map.put(20, "pomelos");
  12. hash_map.put(25, "Welcomes");
  13. hash_map.put(30, "You");
  14. // Displaying the HashMap
  15. System.out.println("Initial Mappings are: " + hash_map);
  16. // Removing the existing key mapping
  17. String returned_value = (String)hash_map.remove(20);
  18. // Verifying the returned value
  19. System.out.println("Returned value is: "+ returned_value);
  20. // Displayin the new map
  21. System.out.println("New map is: "+ hash_map);
  22. }
  23. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. Returned value is: pomelos
  3. New map is: {25=Welcomes, 10=pomelos, 30=You, 15=4}
  1. // 当传递一个新key
  2. // Java code to illustrate the remove() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args) {
  6. // Creating an empty HashMap
  7. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  8. // Mapping string values to int keys
  9. hash_map.put(10, "pomelos");
  10. hash_map.put(15, "4");
  11. hash_map.put(20, "pomelos");
  12. hash_map.put(25, "Welcomes");
  13. hash_map.put(30, "You");
  14. // Displaying the HashMap
  15. System.out.println("Initial Mappings are: " + hash_map);
  16. // Removing the new key mapping
  17. String returned_value = (String)hash_map.remove(50);
  18. // Verifying the returned value
  19. System.out.println("Returned value is: "+ returned_value);
  20. // Displayin the new map
  21. System.out.println("New map is: "+ hash_map);
  22. }
  23. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 3`0=You, 15=4}
  2. Returned value is: null
  3. New map is: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}

13. Collection values():它用于返回HashMap中值的集合视图。

  • 语法 Hash_Map.values()
  • 参数:无参数
  • 返回值:该方法用于返回包含映射的所有值的集合视图。
  • 示例如下:
  1. // 将字符串映射为整数
  2. // Java code to illustrate the values() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<Integer, String> hash_map = new HashMap<Integer, String>();
  9. // Mapping string values to int keys
  10. hash_map.put(10, "pomelos");
  11. hash_map.put(15, "4");
  12. hash_map.put(20, "pomelos");
  13. hash_map.put(25, "Welcomes");
  14. hash_map.put(30, "You");
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using values() to get the set view of values
  18. System.out.println("The collection is: " + hash_map.values());
  19. }
  20. }

输出:

  1. Initial Mappings are: {20=pomelos, 25=Welcomes, 10=pomelos, 30=You, 15=4}
  2. The collection is: [pomelos, Welcomes, pomelos, You, 4]
  1. // 将整数映射成字符串
  2. // Java code to illustrate the values() method
  3. import java.util.*;
  4. public class Hash_Map_Demo {
  5. public static void main(String[] args)
  6. {
  7. // Creating an empty HashMap
  8. HashMap<String, Integer> hash_map = new HashMap<String, Integer>();
  9. // Mapping int values to string keys
  10. hash_map.put("pomelos", 10);
  11. hash_map.put("4", 15);
  12. hash_map.put("pomelos", 20);
  13. hash_map.put("Welcomes", 25);
  14. hash_map.put("You", 30);
  15. // Displaying the HashMap
  16. System.out.println("Initial Mappings are: " + hash_map);
  17. // Using values() to get the set view of values
  18. System.out.println("The collection is: " + hash_map.values());
  19. }
  20. }

输出:

  1. Initial Mappings are: {4=15, pomelos=20, You=30, Welcomes=25}
  2. The collection is: [15, 20, 30, 25]

参考文献:

https://docs.oracle.com/javase/7/docs/api/java/util/HashSet.html

https://www.geeksforgeeks.org/hashset-in-java/

Hash Map 在java中的解释及示例的更多相关文章

  1. 关于Hash集合以及Java中的内存泄漏

    <学习笔记>关于Hash集合以及Java中的内存泄漏 标签: 学习笔记内存泄露hash 2015-10-11 21:26 58人阅读 评论(0) 收藏 举报  分类: 学习笔记(5)  版 ...

  2. hash表及Java中的HashMap与HashSet

    链接: http://alex09.iteye.com/blog/539545/ 当程序试图将一个 key-value 对放入 HashMap 中时,程序首先根据该 key 的 hashCode() ...

  3. Java中的构造函数——通过示例学习Java编程(14)

      作者:CHAITANYA SINGH 来源:https://www.koofun.com//pro/kfpostsdetail?kfpostsid=25 构造函数是用来初始化新创建的对象的代码块. ...

  4. Java中的数据类型——通过示例学习Java编程(5)

    作者:CHAITANYA SINGH 来源:https://www.koofun.com//pro/kfpostsdetail?kfpostsid=15 数据类型用来定义变量可以采用的值,例如,如果变 ...

  5. Java中的变量——通过示例学习Java编程(4)

    作者:CHAITANYA SINGH 来源:https://www.koofun.com/pro/kfpostsdetail?kfpostsid=14&cid= 变量是用来存放可以更改的值的容 ...

  6. ref:关于JAVA中一些安全漏洞示例说明及如何规避方法代码示例总结分享

    ref:http://www.xwood.net/_site_domain_/_root/5870/5874/t_c268166.html 标签:安全,漏洞,健壮,java,SQL注入,SS及CSRF ...

  7. java中的IO 的示例

    字符流 package jd_1; import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileNot ...

  8. java中的定时任务小示例

    package package_1; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Timer; ...

  9. Java中ElasticSearch的删除示例

    public class DeleteElasticAPI { private static RestClient restClient; static { restClient=RestClient ...

随机推荐

  1. ES常用操作备忘

    格式:<REST Verb>/<Index>/<Type>/<ID> 集群健康:curl -u lases:1fw@2soc#3vpn -XGET 'l ...

  2. Mybatis常见配置错误总结

    Mybatis常见配置错误总结 <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionF ...

  3. Python 中文乱码matplotlib乱码 (Windows)

    Python解决matplotlib中文乱码问题(Windows) matplotlib是Python著名的绘图库,默认并不支持中文显示,因此在不经过修改的情况下,无法正确显示中文.本文将介绍如何解决 ...

  4. 【Spring Boot】java.lang.NoSuchMethodError: org.springframework.web.util.UrlPathHelper.getLookupPathForRequest(Ljavax/servlet/http/HttpServletRequest;Ljava/lang/String;)Ljava/lang/String;

    Digest:今天Spring Boot 应用启动成功,访问接口出现如下错误,不知到导致问题关键所在,记录一下这个问题. 浏览器报500错误 项目代码如下 Controller.java packag ...

  5. PHP输出A到Z及相关

    先看以下一段PHP的代码,想下输出结果是什么. <?php for($i='A'; $i<='Z'; $i++) { echo $i . '<br>'; } ?> 输出的 ...

  6. python编程【环境篇】- 如何优雅的管理python的版本

    简介 之前的文章(Python2还是python3 )中我们提到,建议现在大家都采用python3,因为python2在今年年底将不在维护.但在实际的开发和使用python过程中,我们避免不了还得用到 ...

  7. Eclipse SVN插件的帐号、密码修改

    Eclipse的SVN插件Subclipse做得很好,在svn操作方面提供了很强大丰富的功能.但到目前为止,该插件对svn用户的概念极为淡薄,不但不能方便地切换用户,而且一旦用户的帐号.密码保存之后, ...

  8. m74 考试反思

    这次不叫考试题解,叫做考试反思,为什么折磨说,因为这次犯的错误太多了! 事情还要从昨天晚上说起,昨晚放学,班主任来机房说我被子不合格,要停课反思 ###&&¥%#%¥@#%¥#@……% ...

  9. 中文企业云操作系统 CecOS

    CecOS介绍 CecOS(原中文企业云操作系统.第一个版本基于oVirt 3.0,后续在此基础上不断升级迭代拓展至今,已形成基于基础底层和应用功能拓展集成在内的10款产品和四大平台),旨在通过先进的 ...

  10. 腾讯开源进入爆发期,Plato助推十亿级节点图计算进入分钟级时代

    腾讯开源再次迎来重磅项目,14日,腾讯正式宣布开源高性能图计算框架Plato,这是在短短一周之内,开源的第五个重大项目. 相对于目前全球范围内其它的图计算框架,Plato可满足十亿级节点的超大规模图计 ...