zoukankan      html  css  js  c++  java
  • Java容器——Set接口

    1.定义

    set中不允许放入重复的元素(元素相同时只取一个)。使用equals()方法进行比较,如果返回true,两个对象的HashCode值也应该相等。

    2.方法

    TreeSet中常用的方法:

    boolean add(E e):添加一个元素,如果set中不存在该元素

    boolean addAll(Collection<? extends E> c):向set添加集合

    E ceiling(E e):返回大于等于给定元素的最小元素,没有返回null

    void clear():移除所有元素

    Object clone():浅拷贝集合

    boolean contains(Object o):判断set是否包含某元素

    E first():返回set的第一个元素

    E last():返回set的最后一个元素

    E floor(E e):返回给定元素的上一元素

    E higher(E e):返回比给定元素大的最小元素

    E lower(E e):返回比给定元素小的最大元素

    SortedSet<E> headSet(E toElement):返回不包含给定元素前面的所有元素

    SortedSet<E> tailSet(E fromElement):返回大于等于给定元素后面的所有元素

    SortedSet<E> subSet(E fromElement, E toElement):返回开始/结束元素之间的所有元素集合,[from, to)

    NavigableSet<E> headSet(E toElement, boolean inclusive):返回比给定元素小的元素集合,true表示小于等于

    NavigableSet<E> tailSet(E fromElement, boolean inclusive):返回比给定元素大的元素集合,true表示大于等于

    boolean isEmpty():判断set是否为空

    Iterator<E> iterator():返回一个升序的set迭代器

    E pollFirst():移除第一个元素,返回null如果set为空

    E pollLast():移除最后一个元素,返回null如果set为空

    boolean remove(Object o):移除指定元素

    int size():返回集合元素数目

    3.常用实现类

    3.1 HashSet

    1)可以放入空值;

    2)传入元素时,调用HashCode方法获取hash值,然后决定存储位置;

    3.2 LinkedHashSet

    1)HashSet的子类,使用HashCode确定在集合中的位置,使用链表的方式确定位置(有序,按照输入的顺序输出)

    3.3 TreeSet

    1)默认情况下,直接使用TreeSet无参构造器创建Set的对象,在其中放入元素时,必须实现Comparable接口(用于排序),

         按照compareTo方法排序;

    2)若创建TreeSet对象时,传入了一个实现Comparator接口的类,则TreeSet使用Comparator接口的compare方法排序,

         此时集合中的元素无需实现Comparable接口;如果放入了实现Comparable接口的元素,以Comparator为标准 。

    4. 示例         

    4.1 SetFunc.java

      1 import java.util.*;
      2 
      3 public class SetFunc {
      4 
      5     public static void main(String[] args){
      6 
      7         // HashSet
      8         Set<Customer> c1 = new HashSet<>();
      9         c1.add(new Customer(1,"AAA"));
     10         c1.add(new Customer(1,"AAA"));
     11         c1.add(new Customer(2,"AAA"));
     12         c1.add(null);
     13         System.out.println(c1.size());   // 3
     14         for(Customer c:c1){
     15             System.out.println(c);
     16         }
     17 
     18 
     19         // LinkedHashSet
     20         Set<Customer> c2 = new LinkedHashSet<>();
     21         c2.add(new Customer(1,"AAA"));
     22         c2.add(new Customer(3,"CCC"));
     23         c2.add(new Customer(2,"BBB"));
     24         for(Customer c:c2){
     25             System.out.println(c);
     26         }
     27 
     28 
     29         /*
     30         * TreeSet
     31         * 使用TreeSet()构造器
     32         * 需要为Customer类实现Comparable接口,即实现compareTo方法
     33         * */
     34         TreeSet<Customer> c3 = new TreeSet<>();
     35         c3.add(new Customer(1,"AAA"));
     36         c3.add(new Customer(3,"CCC"));
     37         c3.add(new Customer(4,"DDD"));
     38         c3.add(new Customer(5,"EEE"));
     39         Customer b = new Customer(2,"BBB");
     40         for(Customer c:c3){
     41             System.out.println(c);
     42         }
     43 
     44 
     45         // first
     46         Customer a = c3.first();
     47         System.out.println("first: "+a);        // Customer:[Id=1, Name=AAA]
     48         // last
     49         Customer e = c3.last();
     50         System.out.println("last: "+e);        // Customer:[Id=5, Name=EEE]
     51 
     52         // ceiling
     53         Customer ceil1 = c3.ceiling(b);
     54         System.out.println("ceiling: : "+ceil1);    // Customer:[Id=3, Name=CCC]
     55 
     56         // lower
     57         a = c3.lower(b);
     58         System.out.println("lower b: "+a);        // Customer:[Id=1, Name=AAA]
     59         Customer pre = c3.lower(a);
     60         System.out.println("lower a: "+pre);      // null
     61         // higher
     62         Customer c = c3.higher(b);
     63         System.out.println("higher b: "+c);       // Customer:[Id=3, Name=CCC]
     64 
     65         // floor
     66         a = c3.floor(b);
     67         System.out.println("floor b: "+a);      // Customer:[Id=1, Name=AAA]
     68 
     69         // subSet, [from, to)
     70         Set<Customer> c41 = c3.subSet(a, c);
     71         System.out.println("c41: "+c41);
     72 
     73         // headSet, [ , to)
     74         Set<Customer> c42 = c3.headSet(e);
     75         System.out.println("c42: "+c42);
     76         // headSet, [, to]
     77         c42 = c3.headSet(e, true);
     78         System.out.println("c42: "+c42);
     79 
     80         // tailSet, [From, ]
     81         Set<Customer> c43 = c3.tailSet(c);
     82         System.out.println("c43: "+c43);
     83         // tailSet, (from, ]
     84         c43 = c3.tailSet(c, false);
     85         System.out.println("c43: "+c43);
     86 
     87 
     88         /*
     89         * TreeSet
     90         * 使用TreeSet(Comparator<? super E> comparator)构造器
     91         * 需要实现Comparator接口,即实现compare方法
     92         * */
     93         Comparator comparator = new CustomerComparator();
     94         TreeSet<Customer> c5 = new TreeSet<>(comparator);
     95         c5.add(new Customer(1,"AAA"));
     96         c5.add(new Customer(3,"CCC"));
     97         c5.add(new Customer(2,"BBB"));
     98         c5.add(new Customer(4,"DDD"));
     99         for(Customer cus:c5){
    100             System.out.println(cus);
    101         }
    102     }
    103 }
    View Code

    4.2 Customer.java

     1 import java.util.Objects;
     2 
     3 public class Customer implements Comparable<Customer>{
     4 
     5     private int customerId;
     6     private String customerName;
     7 
     8     public Customer(Integer customerId, String customerName) {
     9         this.customerId = customerId;
    10         this.customerName = customerName;
    11     }
    12 
    13     public int getCustomerId() {
    14         return customerId;
    15     }
    16     public String getCustomerName() {
    17         return customerName;
    18     }
    19 
    20     @Override
    21     public String toString() {
    22         return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
    23     }
    24 
    25      /*
    26      * 重写compareTo方法
    27      * 按Id或者name排序
    28      * 可以对整体添加负号决定升降序
    29      * */
    30     @Override
    31     public int compareTo(Customer o) {
    32 //        return this.customerId - o.customerId;
    33         return this.customerName.compareTo(o.customerName);
    34     }
    35 
    36     /*
    37     * 重写equals和hashcode方法
    38     * 这里id和name相同则为同一对象
    39     * */
    40     @Override
    41     public boolean equals(Object o) {
    42         if (this == o) return true;
    43         if (!(o instanceof Customer)) return false;
    44         Customer customer = (Customer) o;
    45         return customerId == customer.customerId &&
    46                 Objects.equals(customerName, customer.customerName);
    47     }
    48 
    49     @Override
    50     public int hashCode() {
    51         return Objects.hash(customerId, customerName);
    52     }
    53 
    54 }
    View Code

    4.3 CustomerComparator.java

     1 import java.util.Comparator;
     2 
     3 public class CustomerComparator implements Comparator<Customer> {
     4 
     5     @Override
     6     public int compare(Customer c1, Customer c2) {
     7         // 按Id排序
     8         return c1.getCustomerId() - c2.getCustomerId();
     9      }
    10 }
    View Code

    !!!

  • 相关阅读:
    Java解析复杂xml文件,使用Xpath
    表达式求值
    解决 error CS0012 错误
    mssql sqlserver 分组排序函数row_number、rank、dense_rank用法简介及说明
    c#核心基础
    Git源代码管理
    CASE 表达式
    NPM -- 初探--01
    ASP.NET Zero--基础设施
    ASP.NET Zero--基于令牌的认证&SWAGGER UI
  • 原文地址:https://www.cnblogs.com/jfl-xx/p/4707540.html
Copyright © 2011-2022 走看看