zoukankan      html  css  js  c++  java
  • java集合类(四)About Set

    接上篇:java集合类(三)About Iterator & Vector(Stack)

         之前,在比较java常见集合类的时候,就了解到一点有关Set的特性、实现类及其要求等,读者可以去温习下“java集合类(一)”。Set与Collection接口完全一样('cause 它继承了Collection接口---接口间继承,可以此拓展接口功能,另外,java只能通过接口实现多继承,而抽象类则不行),只是与Collection的行为不一样(多态性表现)。Set保存的是不重复元素,但不保证元素次序,它常被用来测试归属性,即通过对象的值,判断元素是否在某个Set集合内,通常使用HashSet实现,因为HashSet专门对快速查找进行了优化(hashCode()实现)。另外2种常见的Set,TreeSet则实现Comparable接口,以一定的方式对元素进行排序,并用红黑树存储这些元素;LinkedHashSet也使用了hashCode(),但它使用链表来维护元素顺序---即元素的插入顺序。这三者的比较可见下文!下面介绍Set的使用:

    • Talk about “Set”:
    All Superinterfaces:Collection<E>, Iterable<E> 
    All Known Subinterfaces:NavigableSet<E>, SortedSet<E>
    All Known Implementing Classes:AbstractSet, ConcurrentSkipListSet, CopyOnWriteArraySet, EnumSet, HashSet, JobStateReasons, LinkedHashSet, TreeSet
    1.Set 的常规使用:
    //demo from <Thinking in java>
    import java.util.*;
    
    public void setdemo(){
      Random r = new Random(30);
      Set<Integer> set = new HashSet<Integer>();
      for(int i = 0; i<10000; i++)
          set.add(r.nextInt(20));
      System.out.println(set);
    }
    /*output:
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 16, 19, 18]
    */
    

      上面实例只对add()进行,因为Set跟之前的Collection差不多,其他方法便不再一一演示。在上面代码中使用了Random进行对Set元素的添加,这里就顺便用Set实现“在特定范围内,确保每次产生不同的随机数”

    //Random 5 different nums between 10~100 every time
    
    import java.util.*;
    
    public void randomdemo(){
         HashSet<Integer> hs = new HashSet<Integer>();
         while (true) {
         int a = (int)(Math.random() * 100);
          if(a >= 10 && a <= 100) {
                 hs.add(a);
           }
          if (hs.size() == 5) {
    	      break;
    	 }
         }
         System.out.println(hs);
    }
    //output:[23, 97, 82, 41, 30]
    
    • 关于使用Set测试元素的归属性,主要采用的是contains()及其相关方法,用法跟其他前面提及的java集合类差不多,这里也不作实例演示。  
    • 三种常用Set实现类的比较:

    1)HashSet:  为快速查找而设计的set,存入HashSet的元素必须定义hashCode(),编程中一般使用这种(对元素顺序无要求时)

    2)TreeSet: 保持次序的Set,底层结构为红黑树,使用它可以从Set中提取有序序列,存入其中的元素必须实现Comparable接口

    3)LinkedHashSet:具有HashSet的查询速度,使用链表维护元素的顺序(即插入顺序),元素必须定义hashCode()

    注:关于hashCode(),以后有时间再跟读者详细讨论,现在只需知道:在这里,它是为快速查找而必须实现的方法!

    2.About SortedSet:

    All Superinterfaces:Collection<E>, Iterable<E>, Set<E>
    All Known Subinterfaces:NavigableSet<E>
    All Known Implementing Classes:ConcurrentSkipListSet, TreeSet
    • 有关SortedSet的方法:
      1)Comparator comparator():Returns the comparator used to order the elements in this set, or null if this set uses the natural ordering of its elements

            2)Object first():Returns the first (lowest) element currently in this set

            3)Object last():Returns the last (highest) element currently in this set

            4)SortedSet subSet(fromelement,toelement):

                                Returns a view of the portion of this set whose elements range from fromElement, inclusive, to toElement, exclusive

            5)SortedSet headSet(toelement):Returns a view of the portion of this set whose elements are strictly less than toElement

            6)SortedSet tailSet(fromelement):Returns a view of the portion of this set whose elements are greater than or equal to fromElement

    • SortedSet的示例:
    import java.util.*;
    
    public void sortedsetdemo(){
         SortedSet<String> sortedset = new TreeSet<String>();
         Collections.addAll(sortedset, "1 2 3 4 5".split(" "));
         System.out.println(sortedset);
         System.out.println(sortedset.first());
         System.out.println(sortedset.last());
         System.out.println(sortedset.subSet("1","4"));
         System.out.println(sortedset.headSet("3"));
         System.out.println(sortedset.tailSet("2"));
    } 

    输出:

    [1, 2, 3, 4, 5]
    1
    5
    [1, 2, 3]
    [1, 2]
    [2, 3, 4, 5]

       下一节学习“java集合类(五)About Map”!

    ###    学习从来都是一个过程,对对错错对对...若文中有错误,还望读者批评指出      ###

  • 相关阅读:
    AVR单片机教程——EasyElectronics Library v1.1手册
    C++ lambda的演化
    希尔排序的正确性 (Correctness of ShellSort)
    PAT甲级满分有感
    PAT甲级题分类汇编——杂项
    Python第八章-异常
    Python第七章-面向对象高级
    Python第七章-面向对象初级
    Python第六章-函数06-高阶函数
    Python第六章-函数05-迭代器&生成器
  • 原文地址:https://www.cnblogs.com/allenpengyu/p/3463624.html
Copyright © 2011-2022 走看看