Java中不可变的空集合示例

有时使用不可变空收集是合适的。
有几种方法可以在Java中创建不可变空列表。
不变的空集合类提供以有效方式获得此类集合的方法:

List anEmptyList = Collections.emptyList();
Map anEmptyMap   = Collections.emptyMap();
Set anEmptySet   = Collections.emptySet();

这些方法是通用的,将自动将返回的集合转换为其分配给的类型。
也就是说,调用例如。
emptyList()可以分配给任何类型的列表,同样用于EmptySet()和Emptymap()。

这些方法返回的集合在于,如果我们尝试调用将改变其内容的方法(添加,放置等),则会抛出UnsupportedoperationException。
这些集合主要用作空方法结果或者其他默认值的替代品,而不是使用null或者创建具有新的对象。

子集合

List subList(int fromIndex, int toIndex)

这里fromIndex是包含的,toIndex是排除的。

List list = new ArrayList();
List list1 = list.subList(fromIndex,toIndex);
  • 如果在给出范围内没有存在列表,则会抛出IndexOutofboundException。
  • 在List1上进行的更改将影响列表中的相同变更。这是称为备份集合。
  • 如果fromnIndex大于toindex(fromindex> toindex),它会抛出IllegalAlargumentException。

例子:

List list = new ArrayList();
List list = new ArrayList();
list.add("Hello1");
list.add("Hello2");
System.out.println("Before Sublist "+list);
List list2 = list.subList(0, 1);
list2.add("Hello3");
System.out.println("After sublist changes "+list);
Output:
Before Sublist [Hello1, Hello2]
After sublist changes [Hello1, Hello3, Hello2]
Set subSet(fromIndex,toIndex)

这里fromIndex是包含的,toIndex是排除的。

Set set = new TreeSet();
Set set1 = set.subSet(fromIndex,toIndex);

返回的集将抛出IllegalArgumentException,尝试在其范围之外插入一个元素。

Map subMap(fromKey,toKey)

这里fromKey是包含的,toKey是排除的。

Map map = new TreeMap();
Map map1 = map.get(fromKey,toKey);

如果从key大于tokey或者此映射本身具有限制范围,并且从键或者涂鸦留出在范围的范围之外,那么它会引发IllowalArgumentException。

所有集合都支持备份集合意味着在子集合上的更改将在主集合上具有相同的更改。

日期:2020-06-02 22:15:19 来源:oir作者:oir