在Java中,判断Map是否为null或者空有以下几种方式:

  1. 使用==操作符检查Map对象是否为null。
  2. 使用isEmpty()方法检查Map是否为空。
  3. 使用size()方法检查Map的大小是否为0。
  4. 使用Collections.isEmpty()方法检查Map是否为空。

示例代码:

import java.util.HashMap;
import java.util.Map;
import java.util.Collections;

public class Main {
    public static void main(String[] args) {
        Map<String, String> map = null; // 示例:将map设置为null

        // 方法1:使用 == 操作符检查Map对象是否为null
        if (map == null) {
            System.out.println("Map is null");
        } else {
            // 方法2:使用 isEmpty() 方法检查Map是否为空
            if (map.isEmpty()) {
                System.out.println("Map is empty");
            } else {
                System.out.println("Map is not empty");
            }
        }

        // 方法3:使用 size() 方法检查Map的大小是否为0
        map = new HashMap<>();
        if (map.size() == 0) {
            System.out.println("Map is empty");
        } else {
            System.out.println("Map is not empty");
        }

        // 方法4:使用 Collections.isEmpty() 方法检查Map是否为空
        map = new HashMap<>();
        if (Collections.isEmpty(map)) {
            System.out.println("Map is empty");
        } else {
            System.out.println("Map is not empty");
        }
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.