【OCJP】 第2题---Set中subSet()方法的运用

题目:

QUESTION 4
Given:
12. import java.util.*;
13. public class Explorer2 {
14. public static void main(String[] args) {
15. TreeSet<Integer> s = new TreeSet<Integer>();
16. TreeSet<Integer> subs = new TreeSet<Integer>();
17. for(int i = 606; i < 613; i++)
18. if(i%2 == 0) s.add(i);
19. subs = (TreeSet)s.subSet(608, true, 611, true);
20. s.add(629);
21. System.out.println(s + " " + subs);
22. }
23. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. [608, 610, 612, 629] [608, 610]
D. [608, 610, 612, 629] [608, 610, 629]
E. [606, 608, 610, 612, 629] [608, 610]
F. [606, 608, 610, 612, 629] [608, 610, 629]
Answer: E


本题主要考查:

1、TreeSet 自然排序

2、subSet()方法的运用

先来看下subSet():

NavigableSet<Integer> java.util.TreeSet.subSet(Integer fromElement, boolean fromInclusive, Integer toElement, boolean toInclusive)


Returns a view of the portion of this set whose elements range from fromElement to toElement.  The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports. 

The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.


返回一个视图的一部分从fromElement到toElement这个集合的元素。如果fromElement 和toElement是相等的,返回的集合是空的,除非fromInclusive和toInclusive都是true。返回的集合是由这个集合backed的,所以返回的变化反映在这个集合,反之亦然。返回的集合支持支持原集合所有可选的设置操作。

返回的集合将抛出IllegalArgumentException,当试图插入一个元素以外的范围。


理论说完了,现在实践一下。

先把题目回顾一遍,有两个TreeSet集合s 和 subs,s里边有[606, 608, 610, 612],subs 是用 subSet()得来的,[608, 610];然后再向 s 中添加一个629,因不是往subs中添加,故不会报IllegalArgumentException。最终 s 就是 [608, 610, 612, 629], subs就是 [608, 610]。


下面我们稍稍修改下,


因为都是true,所以subs中608和610都有。


再改下。


这个就是If fromElement and toElement are equal, the returned set is empty unlessfromInclusive andtoInclusive are both true. 


再改下:



这个就像映射一样,反之亦然,下图也是这个原理。



下边这个直接向subs中添加超出了它范围的数字,报IllegalArgumentException异常。原题目是向 s 中添加是没有问题的。




  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值