zoukankan      html  css  js  c++  java
  • TreeSet 题

    QUESTION 4Given:
    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 中添加是没有问题的。

  • 相关阅读:
    init: cannot execve(‘XXX’):Permission denied问题
    Android自己定义之流式布局
    GDI+学习笔记(九)带插件的排序算法演示器(MFC中的GDI+实例)
    SICP 习题 (2.8) 解题总结:区间的减法
    Web
    this 与 super 反复问题?
    [Android&amp;Java]浅谈设计模式-代码篇:观察者模式Observer
    053第170题
    SonarQube4.4+Jenkins进行代码检查实例之三-单元測试分析
    总结Codeigniter的一些优秀特性
  • 原文地址:https://www.cnblogs.com/pangpanghuan/p/5582267.html
Copyright © 2011-2022 走看看