温馨提示×

java怎么判断map是否为空

小亿
109
2023-12-18 12:01:57
栏目: 编程语言

要判断一个Map是否为空,可以使用 isEmpty() 方法来判断。该方法会返回一个布尔值,如果Map为空,则返回 true;否则返回 false。

以下是一个示例代码:

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

public class Main {
    public static void main(String[] args) {
        // 创建一个空的Map
        Map<String, Integer> map = new HashMap<>();

        // 判断Map是否为空
        if (map.isEmpty()) {
            System.out.println("Map is empty");
        } else {
            System.out.println("Map is not empty");
        }

        // 添加一个元素到Map中
        map.put("key", 1);

        // 再次判断Map是否为空
        if (map.isEmpty()) {
            System.out.println("Map is empty");
        } else {
            System.out.println("Map is not empty");
        }
    }
}

输出结果:

Map is empty
Map is not empty

在上述示例中,我们首先创建了一个空的Map。然后使用 isEmpty() 方法来判断Map是否为空,并打印相应的信息。之后,添加了一个元素到Map中,再次使用 isEmpty() 方法判断Map是否为空,并打印相应的信息。

0