Java如何创建空的集合对象?
有时您需要从Java方法返回一个空集合。java.util.Collections实用工具类具有创建空的三个不同的静态常量List,Set和Map。
Collections.EMPTY_LIST
Collections.EMPTY_SET
Collections.EMPTY_MAP
当您要创建类型安全的空集合时,还有一些方法。
Collections.emptyList()
Collections.emptySet()
Collections.emptyMap()
下面是代码示例。
package org.nhooo.example.util; import java.util.*; public class EmptyCollectionDemo { public static void main(String args[]) { List list = Collections.EMPTY_LIST; System.out.println("list.size() = " + list.size()); Set set = Collections.EMPTY_SET; System.out.println("set.size() = " + set.size()); Map map = Collections.EMPTY_MAP; System.out.println("map.size() = " + map.size()); // 对于类型安全的示例,请使用以下方法。 List<String> strings = Collections.emptyList(); System.out.println("strings.size = " + strings.size()); Set<Long> longs = Collections.emptySet(); System.out.println("longs.size() = " + longs.size()); Map<String, Date> dates = Collections.emptyMap(); System.out.println("dates.size() = " + dates.size()); } }
输出为:
list.size() = 0 set.size() = 0 map.size() = 0 strings.size = 0 longs.size() = 0 dates.size() = 0