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

 import java.util.*;

 public class SetFunc {

     public static void main(String[] args){

         // HashSet
Set<Customer> c1 = new HashSet<>();
c1.add(new Customer(1,"AAA"));
c1.add(new Customer(1,"AAA"));
c1.add(new Customer(2,"AAA"));
c1.add(null);
System.out.println(c1.size()); //
for(Customer c:c1){
System.out.println(c);
} // LinkedHashSet
Set<Customer> c2 = new LinkedHashSet<>();
c2.add(new Customer(1,"AAA"));
c2.add(new Customer(3,"CCC"));
c2.add(new Customer(2,"BBB"));
for(Customer c:c2){
System.out.println(c);
} /*
* TreeSet
* 使用TreeSet()构造器
* 需要为Customer类实现Comparable接口,即实现compareTo方法
* */
TreeSet<Customer> c3 = new TreeSet<>();
c3.add(new Customer(1,"AAA"));
c3.add(new Customer(3,"CCC"));
c3.add(new Customer(4,"DDD"));
c3.add(new Customer(5,"EEE"));
Customer b = new Customer(2,"BBB");
for(Customer c:c3){
System.out.println(c);
} // first
Customer a = c3.first();
System.out.println("first: "+a); // Customer:[Id=1, Name=AAA]
// last
Customer e = c3.last();
System.out.println("last: "+e); // Customer:[Id=5, Name=EEE] // ceiling
Customer ceil1 = c3.ceiling(b);
System.out.println("ceiling: : "+ceil1); // Customer:[Id=3, Name=CCC] // lower
a = c3.lower(b);
System.out.println("lower b: "+a); // Customer:[Id=1, Name=AAA]
Customer pre = c3.lower(a);
System.out.println("lower a: "+pre); // null
// higher
Customer c = c3.higher(b);
System.out.println("higher b: "+c); // Customer:[Id=3, Name=CCC] // floor
a = c3.floor(b);
System.out.println("floor b: "+a); // Customer:[Id=1, Name=AAA] // subSet, [from, to)
Set<Customer> c41 = c3.subSet(a, c);
System.out.println("c41: "+c41); // headSet, [ , to)
Set<Customer> c42 = c3.headSet(e);
System.out.println("c42: "+c42);
// headSet, [, to]
c42 = c3.headSet(e, true);
System.out.println("c42: "+c42); // tailSet, [From, ]
Set<Customer> c43 = c3.tailSet(c);
System.out.println("c43: "+c43);
// tailSet, (from, ]
c43 = c3.tailSet(c, false);
System.out.println("c43: "+c43); /*
* TreeSet
* 使用TreeSet(Comparator<? super E> comparator)构造器
* 需要实现Comparator接口,即实现compare方法
* */
Comparator comparator = new CustomerComparator();
TreeSet<Customer> c5 = new TreeSet<>(comparator);
c5.add(new Customer(1,"AAA"));
c5.add(new Customer(3,"CCC"));
c5.add(new Customer(2,"BBB"));
c5.add(new Customer(4,"DDD"));
for(Customer cus:c5){
System.out.println(cus);
}
}
}

4.2 Customer.java

 import java.util.Objects;

 public class Customer implements Comparable<Customer>{

     private int customerId;
private String customerName; public Customer(Integer customerId, String customerName) {
this.customerId = customerId;
this.customerName = customerName;
} public int getCustomerId() {
return customerId;
}
public String getCustomerName() {
return customerName;
} @Override
public String toString() {
return "Customer:[Id=" + customerId + ", Name=" + customerName + "]";
} /*
* 重写compareTo方法
* 按Id或者name排序
* 可以对整体添加负号决定升降序
* */
@Override
public int compareTo(Customer o) {
// return this.customerId - o.customerId;
return this.customerName.compareTo(o.customerName);
} /*
* 重写equals和hashcode方法
* 这里id和name相同则为同一对象
* */
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Customer)) return false;
Customer customer = (Customer) o;
return customerId == customer.customerId &&
Objects.equals(customerName, customer.customerName);
} @Override
public int hashCode() {
return Objects.hash(customerId, customerName);
} }

4.3 CustomerComparator.java

 import java.util.Comparator;

 public class CustomerComparator implements Comparator<Customer> {

     @Override
public int compare(Customer c1, Customer c2) {
// 按Id排序
return c1.getCustomerId() - c2.getCustomerId();
}
}

!!!

Java容器——Set接口的更多相关文章

  1. Java容器Map接口

    Map接口容器存放的是key-value对,由于Map是按key索引的,因此 key 是不可重复的,但 value 允许重复. 下面简单介绍一下Map接口的实现,包括HashMap,LinkedHas ...

  2. Java容器List接口

    List接口是Java中经常用到的接口,如果对具体的List实现类的特性不了解的话,可能会导致程序性能的下降,下面从原理上简单的介绍List的具体实现: 可以看到,List继承了Collection接 ...

  3. Java容器---Collection接口中的共有方法

    1.Collection 接口 (1)Collection的超级接口是Iterable (2)Collection常用的子对象有:Map.List.Set.Queue. 右图中实现黑框的ArrayLi ...

  4. Java容器——List接口

    1. 定义 List是Collection的子接口,元素有序并且可以重复,表示线性表. 2. 常用实现类 ArrayList:它为元素提供了下标,可以看作长度可变的数组,为顺序线性表. LinkedL ...

  5. java容器——Collection接口

    Collection是Set,List接口的父类接口,用于存储集合类型的数据. 2.方法 int size():返回集合的长度 void clear():清除集合里的所有元素,将集合长度变为0 Ite ...

  6. Java容器——Map接口

    1.定义 Map用于保存存在映射关系<key, value>的数据.其中key值不能重复(使用equals()方法比较),value值可以重复. 2.常用实现类 HashMap:和Hash ...

  7. Java容器Set接口

    Set接口的实现,可以方便地将指定的类型以集合类型保存在一个变量中.Set是一个不包含重复元素的Collection,更确切地讲,Set 不包含满足 e1.equals(e2) 的元素对,并且最多包含 ...

  8. Java容器深入浅出之Collection与Iterator接口

    Java中用于保存对象的容器,除了数组,就是Collection和Map接口下的容器实现类了,包括用于迭代容器中对象的Iterator接口,构成了Java数据结构主体的集合体系.其中包括: 1. Co ...

  9. 【Java心得总结七】Java容器下——Map

    我将容器类库自己平时编程及看书的感受总结成了三篇博文,前两篇分别是:[Java心得总结五]Java容器上——容器初探和[Java心得总结六]Java容器中——Collection,第一篇从宏观整体的角 ...

随机推荐

  1. Win32 实现 MFC CFileDialog 对话框

    void CWriteWnd::OpenFileDialog() { OPENFILENAME ofn; TCHAR szFile[MAX_PATH] = _T(""); Zero ...

  2. HDU 1823 Luck and Love (二维线段树&区间最值)题解

    思路: 树套树,先维护x树,再维护y树,多练练应该就能懂了 代码: #include<cstdio> #include<cmath> #include<cstring&g ...

  3. 51nod 1137 矩阵乘法

    基本的矩阵乘法 中间for(int j=0;i<n;i++)  //这里写错了   应该是j<n 晚上果然  效率不行 等会早点儿睡 //矩阵乘法 就是 两个矩阵 第一个矩阵的列 等与 第 ...

  4. C#用Linq查询Combox的数据源

    https://www.cnblogs.com/sufei/archive/2010/01/12/1645763.html var result =  ((DataTable) (this.ComSh ...

  5. CSAPP学习笔记 第一章 计算机系统漫游

    Ch 1.0 1.计算机系统是由硬件和系统软件组成的 2.本书阐述了计算机组件是如何工作的以及执行组件是如何影响程序正确性和性能的. 3.通过跟踪hello程序的生命周期来开始对系统的学习. #inc ...

  6. BZOJ 1009: [HNOI2008]GT考试(kmp+dp+矩阵优化)

    http://www.lydsy.com/JudgeOnline/problem.php?id=1009 题意: 思路:真的是好题啊! 对于这种题目,很有可能就是dp,$f[i][j]$表示分析到第 ...

  7. Ubuntu禁用触摸板

    参考链接: http://www.linuxidc.com/Linux/2012-08/68831.htm http://blog.sina.com.cn/s/blog_a3052b4a0100z4u ...

  8. ubuntu 14.04 server(amd64) 安装ros indigo

    1.添加软件源(添加了正确的软件源,操作系统就知道去哪里下载程序,并根据命令自动安装软件) sudo sh -c 'echo "deb http://packages.ros.org/ros ...

  9. VC++异常处理

    1.测试代码: #include <stdio.h> #include <windows.h> void main() { __try { DWORD dwDemonObj = ...

  10. java开源类库pinyin4j的使用

    最近CMS系统为了增加查询的匹配率,需要增加拼音检索字段,在网上找到了pinyin4j的java开源类库,提供中文转汉语拼音(并且支持多音字), 呵呵,看了看他的demo,决定就用它了,因为我在实际使 ...