原文: https://beginnersbook.com/2014/08/how-to-check-if-a-hashmap-is-empty-or-not/

描述

用于检查HashMap是否为空的程序。我们使用HashMap类的isEmpty()方法来执行此检查。

程序

  1. import java.util.HashMap;
  2. class HashMapIsEmptyExample{
  3. public static void main(String args[]) {
  4. // Create a HashMap
  5. HashMap<Integer, String> hmap = new HashMap<Integer, String>();
  6. // Checking whether HashMap is empty or not
  7. /* isEmpty() method signature and description -
  8. * public boolean isEmpty(): Returns true if this map
  9. * contains no key-value mappings.
  10. */
  11. System.out.println("Is HashMap Empty? "+hmap.isEmpty());
  12. // Adding few elements
  13. hmap.put(11, "Jack");
  14. hmap.put(22, "Rock");
  15. hmap.put(33, "Rick");
  16. hmap.put(44, "Smith");
  17. hmap.put(55, "Will");
  18. // Checking again
  19. System.out.println("Is HashMap Empty? "+hmap.isEmpty());
  20. }
  21. }

输出:

  1. Is HashMap Empty? true
  2. Is HashMap Empty? false