Java中使用isEmpty()方法检查NavigableMap是否为空。
首先,创建一个NavigableMap并向其中添加元素-
NavigableMap<Integer, String> n = new TreeMap<Integer, String>(); n.put(5, "Tom"); n.put(9, "John"); n.put(14, "Jamie"); n.put(1, "Tim"); n.put(4, "Jackie"); n.put(15, "Kurt"); n.put(19, "Tiger"); n.put(24, "Jacob");
现在,检查映射是否为空-
System.out.println("Map is empty? " + n.isEmpty());
以下是实现isEmpty()方法并检查Map是否为空的示例-
import java.util.*; public class Demo { public static void main(String[] args) { NavigableMap<Integer, String> n = new TreeMap<Integer, String>(); n.put(5, "Tom"); n.put(9, "John"); n.put(14, "Jamie"); n.put(1, "Tim"); n.put(4, "Jackie"); n.put(15, "Kurt"); n.put(19, "Tiger"); n.put(24, "Jacob"); System.out.println("NavigableMap elements = "+n); System.out.println("Size = "+n.size()); System.out.println("Map is empty? " + n.isEmpty()); // remove all elements n.clear(); System.out.println("\nUpdated NavigableMap elements = "+n); System.out.println("Size = "+n.size()); System.out.println("Map is empty? " + n.isEmpty()); } }
输出结果
NavigableMap elements = {1=Tim, 4=Jackie, 5=Tom, 9=John, 14=Jamie, 15=Kurt, 19=Tiger, 24=Jacob} Size = 8 Map is empty? false Updated NavigableMap elements = {} Size = 0 Map is empty? True