文章目录
set接口
set接口概述
set接口作为collection接口的子接口,用于存储无序的、不可重复的数据。
其实现类有
HashSet:set接口的主要实现类,线程不安全,可以存储NULL。
LinkedHashSet:HashSet的子类,遍历内部数据时,可以按照添加顺序遍历。
TreeSet:可以按照添加对象的属性进行排序。
set接口的特点
不可重复性::保证添加的元素按equals()判断时,不能返回true。即不能有相同的数据。
无序性:不等于随机性,存储的数据在底层数组中并非按照数组的索引的顺序添加,而是根据数据哈希值决定的。
set接口底层添加元素过程——以HashSet为例
我们向HashSet中添加元素a,首先调用元素a所在类的hashCold()方法,计算a的哈希值.此哈希值通过某种算法计算出
HashSet底层数组中存放的位置(即:索引位置),判断此位置上是否已有元素,
如果此位置上没有元素,则a添加成功。 若有其他元素B(以链表形式存放多个元素),则比较元素a和B的哈希值,若不相同,则a添加成功 (链表形式存放)。若相同,调用元素a所在类的equals()方法。 若返回true,元素重复,添加失败。若返回false,元素添加成功 (链表形式存放)。
set接口遍历方式
作为collection接口的子接口,其遍历方式与collection一致
public static void test01(){
HashSet hashSet = new HashSet();
hashSet.add(456);
hashSet.add(1234);
hashSet.add(456);
hashSet.add("aklds");
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
set接口的常用方法
set接口作为collection的子接口,并未增加新的方法。其主要方法还是collection的方法。
LinkHashset
作为HashSet的子类。在添加数据的同时,每个数据还有维护其前驱和后继。
public static void test02(){
HashSet hashSet = new LinkedHashSet();
hashSet.add(456);
hashSet.add(1234);
hashSet.add(456);
hashSet.add("aklds");
Iterator iterator = hashSet.iterator();
while (iterator.hasNext()){
System.out.println(iterator.next());
}
}
TreeSet
1、向TreeSet中添加对象,必须是同一种类,不同类的对象无法一起添加
2、两种排序:自然排序(实现Comparable接口)和定制排序(comparator)
3、自然排序中,比较两个对象是否相同的标准:compareTo()返回0,不再是equals()方法
4、定制排序中,比较两个对象是否相同的标准:compare()返回0,不再是equals()方法*
public static void Test02(){
TreeSet treeSet = new TreeSet();
treeSet.add(new Person("lan"));
treeSet.add(new Person("cao"));
treeSet.add(new Person("hu"));
treeSet.add(new Person("li"));
Iterator iterator = treeSet.iterator();
while(iterator.hasNext()){
System.out.println(iterator.next());//从小到大排序
}
}
public class Person implements Comparable {
String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Person)) return false;
Person person = (Person) o;
return name.equals(person.name);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override //按照姓名从小到大排序
public int compareTo(Object o) {
if(o instanceof Person){
Person person=(Person) o;
return this.name.compareTo(person.name);
}else{
throw new RuntimeException("输入类型不匹配");
}
}
}