Set接口的介绍
Set接口基本介绍
- 无序(添加和取出的顺序不一致),没有索引
- 不允许重复元素,所以最多包含一个null
- JDK API中Set接口的实现类:主要有HashSet;TreeSet
Set接口的常用方法
和List 接口一样,Set接口也是Collection的子接口,因此,常用方法和Collection接口一样
Set接口的遍历方式
同Collection一致,因为Set是Collection的子接口
- 迭代器
- 增强for
- 不能使用索引的方式
Set接口的常用方法举例
public class SetMethod {
@SuppressWarnings({"all"})
public static void main(String[] args) {
//1. 以 Set 接口的实现类 HashSet 来讲解 Set 接口的方法
//2. set 接口的实现类的对象(Set 接口对象), 不能存放重复的元素, 可以添加一个 null
//3. set 接口对象存放数据是无序(即添加的顺序和取出的顺序不一致)
//4. 注意:取出的顺序的顺序虽然不是添加的顺序,但是他是固定的.
HashSet set = new HashSet();
set.add("john");
set.add("lucy");
set.add("john");//重复
set.add("jack");
set.add("hsp");
set.add("mary");
set.add(null);//
set.add(null);//再次添加 null
// for (int i = 0; i < 10; i++) {
// System.out.println(set);
// }
//遍历
//1,使用迭代器
System.out.println("======使用迭代器=====");
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object object = iterator.next();
System.out.println(object);
}
//2,使用增强for循环
System.out.println("======使用增强for循环=====");
for (Object o:set){
System.out.println(o);
}
//3,不能用普通for ,因为set对象不能调用get方法。不能通过索引来获取
}
}
结果
Set接口实现类-HashSet
HashSet 的全面说明
- HashSet 实现了Set接口
- HashSet实际上是HashMap,源码
- 可以存放null值,但是只能有一个null
- HashSet不保证元素是有序的,取决于hash后,再确定索引的结果(即:不保证存放元素的顺序和取出的顺序一致)
- 不能有重复元素/对象
public class HashSet_ {
@SuppressWarnings({"all"})
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(null);
hashSet.add(null);
System.out.println("hashSet="+hashSet);
}
}
结果
案例说明
public class HashSet01 {
@SuppressWarnings({"all"})
public static void main(String[] args) {
HashSet set = new HashSet();
/**
* 说明:
* 1,在执行add方法后,会返回一个boolean值
* 2,如果添加成功,返回true,否则返回false
*/
System.out.println(set.add("john"));//T
System.out.println(set.add("lucy"));//T
System.out.println(set.add("john"));//F
System.out.println(set.add("jack"));//T
System.out.println(set.add("Rose"));//T
//3,调用remove方法,直接删除对象
set.remove("john");
System.out.println("set="+set);//Rose, lucy, jack
set = new HashSet();
System.out.println(set);//空
//4,Hashset 不能添加相同的元素/数据
set.add("lucy");//添加成功T
set.add("lucy");//加入不了F
set.add(new Dog("tom"));
set.add(new Dog("tom"));//不同的对象
System.out.println(set);
}
}
class Dog{
private String name;
public Dog(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
结果
Set接口实现类-LinkedHashSet
LinkedHashSet的全面说明
- LinkedHashSet 是HashSet的子类
- LinkedHashSet底层是一个LinkedHashMap,底层维护了一个数组+双向链表
- LinkedHashSet根据元素的hashCode值来决定元素的存储位置,同时使用链表维护元素的次序,这使得元素看起来是一插入顺序保存的
- LinkedHashSet不允许添加重复元素