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
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接口的更多相关文章
- Java容器Map接口
Map接口容器存放的是key-value对,由于Map是按key索引的,因此 key 是不可重复的,但 value 允许重复. 下面简单介绍一下Map接口的实现,包括HashMap,LinkedHas ...
- Java容器List接口
List接口是Java中经常用到的接口,如果对具体的List实现类的特性不了解的话,可能会导致程序性能的下降,下面从原理上简单的介绍List的具体实现: 可以看到,List继承了Collection接 ...
- Java容器---Collection接口中的共有方法
1.Collection 接口 (1)Collection的超级接口是Iterable (2)Collection常用的子对象有:Map.List.Set.Queue. 右图中实现黑框的ArrayLi ...
- Java容器——List接口
1. 定义 List是Collection的子接口,元素有序并且可以重复,表示线性表. 2. 常用实现类 ArrayList:它为元素提供了下标,可以看作长度可变的数组,为顺序线性表. LinkedL ...
- java容器——Collection接口
Collection是Set,List接口的父类接口,用于存储集合类型的数据. 2.方法 int size():返回集合的长度 void clear():清除集合里的所有元素,将集合长度变为0 Ite ...
- Java容器——Map接口
1.定义 Map用于保存存在映射关系<key, value>的数据.其中key值不能重复(使用equals()方法比较),value值可以重复. 2.常用实现类 HashMap:和Hash ...
- Java容器Set接口
Set接口的实现,可以方便地将指定的类型以集合类型保存在一个变量中.Set是一个不包含重复元素的Collection,更确切地讲,Set 不包含满足 e1.equals(e2) 的元素对,并且最多包含 ...
- Java容器深入浅出之Collection与Iterator接口
Java中用于保存对象的容器,除了数组,就是Collection和Map接口下的容器实现类了,包括用于迭代容器中对象的Iterator接口,构成了Java数据结构主体的集合体系.其中包括: 1. Co ...
- 【Java心得总结七】Java容器下——Map
我将容器类库自己平时编程及看书的感受总结成了三篇博文,前两篇分别是:[Java心得总结五]Java容器上——容器初探和[Java心得总结六]Java容器中——Collection,第一篇从宏观整体的角 ...
随机推荐
- bzoj1704 / P2882 [USACO07MAR]面对正确的方式Face The Right Way
P2882 [USACO07MAR]面对正确的方式Face The Right Way $n<=5000$?枚举翻转长度,顺序模拟就ok了 对于每次翻转,我们可以利用差分的思想,再搞搞前缀和. ...
- P2158/bzoj2190 [SDOI2008]仪仗队
P2158 [SDOI2008]仪仗队 欧拉函数 计算下三角的点数再*2+1 观察斜率,自行体会 #include<iostream> #include<cstdio> #in ...
- linux虚拟机中安装vm_tool的方法及用处
解决问题:实现虚拟机VMware上linux与windows互相自由复制与粘贴.如在同一个系统下ctrl+c 与ctrl+v一样方便.解决了只能通过U盘摆渡复制的繁琐问题. 系统环境: 虚拟机VMwa ...
- 20145305 《网络对抗》Web安全基础实践
实践过程及结果截图 Phishing with XSS 在文本框里面写一个钓鱼网站代码就可以了 </form> <script> function hack(){ XSSIma ...
- GD32芯片移植完全攻略
GD32是国产兆易创新公司生产的完全兼容STM32系列的Cortex-M3处理器,具有几大亮点:1,高主频108MHz.性能提升30%以上,可超频到120MHz2,Flash零等待.STM32的72M ...
- bzoj 4033 树上染色 - 树形动态规划
有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑 色,并将其他的N-K个点染成白色.将所有点染色后,你会获得黑点两两之间的距离加上白点两两之间距离的 ...
- noip2015 day1
不解释,很简单,直接按照题目的方法构造就行了 Code #include<iostream> #include<cstdio> #include<cctype> # ...
- BZOJ 2594 水管局长数据加强版(动态树)
题目链接:http://61.187.179.132/JudgeOnline/problem.php?id=2594 题意:给出一个无向图,边有权值.定义一条路径的长度为该路径所有边的最大值.两种操作 ...
- C# 将 Stream 写入文件
public void StreamToFile(Stream stream,string fileName) { // 把 Stream 转换成 byte[] byte[] bytes = new ...
- Python数据分析入门之pandas基础总结
Pandas--"大熊猫"基础 Series Series: pandas的长枪(数据表中的一列或一行,观测向量,一维数组...) Series1 = pd.Series(np.r ...