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

!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM