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,第一篇从宏观整体的角 ...
随机推荐
- 使整个页面变灰的css代码
* { filter:progid:DXImageTransform.Microsoft.BasicImage(grayscale=); -webkit-filter: grayscale(%); - ...
- libcurl HTTP POST请求向服务器发送json数据
转载:http://blog.csdn.net/dgyanyong/article/details/14166217 转载:http://blog.csdn.net/th_gsb/article/de ...
- 设置控件如ImageButton可见与否
继承view的控件有三种ui属性: 1.setVisibility(View.Gone); 不可见,不占有空间 2.setVisibility(View.VISIBLE); 可见 3.setVisib ...
- C# 取form表单的数据
//key代表form表单中html元素的name属性值 public static string StringForm(string key) { string result = null; res ...
- Python3基础 str swapcase 英文字母大小写反转
Python : 3.7.0 OS : Ubuntu 18.04.1 LTS IDE : PyCharm 2018.2.4 Conda ...
- Jackson 使用和注意项
依赖maven: <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId ...
- SpringBoot中的Quartz应用
Spring自带定时器任务: code: import org.springframework.beans.factory.annotation.Configurable; import org.sp ...
- POJ 2352 Stars(树状数组)题解
Language:Default Stars Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 52268 Accepted: 22 ...
- 03_Kafka集群操作
1.集群配置思路 1)每台节点上要启动一个broker进程,因此要配置每台的server.properties broker id, log.dirs, zookeeper.connect 2) 每台 ...
- web前端小数点位数处理