Set接口和常用方法
Set接口基本介绍
- 无序(添加和取出的顺序不一致),没有索引
-
不允许重复元素,所以最多包含一个null
-
JDK API中Set接口的实现类有:
Set接口的常用方法
和List接口一样,Set接口也是Collection的子接口,因此,常用方法和Collection接口一样.
Set接口的遍历方式
同Collection的遍历方式一样,因为Set接口是Collection接口的子接口。
1.可以使用迭代器
2.增强for
3.不能使用索引的方式来获取.
package www.xz.set_;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class SetMethod {
public static void main(String[] args) {
//1.以Set接口的实现类HashSet 来演示Set接口的方法
//2.set 接口的 实现类的 对象(Set接口对象),不能存放重复的元素,可以添加一个 null
//3.set 接口对象存放数据是无序的(即添加的顺序和取出的顺序不一致)
//4.注意:取出的顺序的顺序虽然不是添加的顺序,但是他的顺序是固定的。
Set set = new HashSet();
set.add("john");
set.add("lucy");
set.add("john");//重复
set.add("jack");
set.add("xz");
set.add(null);
set.add(null);//重复
System.out.println("set=" + set);
//进行遍历
System.out.println("====迭代器遍历====");
Iterator iterator = set.iterator();
while (iterator.hasNext()) {
Object next = iterator.next();
System.out.println("next=" + next);
}
set.remove(null);
System.out.println("====增强for遍历====");
for (Object o : set) {
System.out.println("o=" + o);
}
//set 接口对象,不能通过索引来获取
//换言之,set 接口对象不可以用普通for进行遍历
}
}
Set接口实现类- HashSet
HashSet的全面说明
-
HashSet实现了Set接口
-
HashSet实际上是HashMap
public HashSet() {
map = new HashMap<>();
}
- 可以存放null值,但是只能有一个null
-
HashSet不保证元素是有序的,取决于hash后,再确定索引的结果。
-
不能有重复元素/对象.在前面Set接口使用提到过
package www.xz.set_;
import java.util.HashSet;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashSet01 {
public static void main(String[] args) {
HashSet set = new HashSet();
System.out.println(set.add("john"));
System.out.println(set.add("lucy"));
System.out.println(set.add("john"));
System.out.println(set.add("jack"));
System.out.println(set.add("Rose"));
set.remove("john");
System.out.println("set=" + set);
set = new HashSet();
System.out.println("set=" + set);
set.add("lucy");//添加成功
set.add("lucy");//添加不了:因为lucy是存放在常量池中的,上面的添加过之后下面的无法添加
set.add(new Dog("tom"));//OK
set.add(new Dog("tom"));//OK 两个Dog并不是同一个对象
System.out.println("set" + set);
//再次加深理解!非常经典的面试题
//看源码,做分析 看完源码就会了然
set.add(new String("xz"));//OK
set.add(new String("xz"));//加入不了
System.out.println("set=" + set);
}
}
class Dog {
private String name;
public Dog(String name) {
this.name = name;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
'}';
}
}
HashSet底层机制说明
➢分析HashSet底层是HashMap, HashMap底层是(数组+链表+红黑树)
简单的数组+链表结构如图:
package www.xz.set_;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashSetStructure {
public static void main(String[] args) {
//模拟个HashSet的底层 (HashMap的底层结构)
//1. 创建一个数组,数组的类型是Node[]
//2. 有些人,直接把Node[]数组称为 表
Node[] table = new Node[16];
System.out.println("table=" + table);
//3.创建节点
Node john = new Node("john", null);
table[2] = john;
Node jack = new Node("jack", null);
john.next = jack;//将jack 结点挂载到john
Node rose = new Node("Rose", null);
jack.next = rose;//将rose 结点挂载到jack
Node lucy = new Node("lucy", null);
table[3] = lucy;//把Lucy放到table表的索引为3的位置。
System.out.println("table=" + table);
}
}
class Node {//结点,存储数据,可以指向下一个结点,从而形成链表
Object item;//存放数据
Node next; //指向下一个结点
public Node(Object item, Node next) {
this.item = item;
this.next = next;
}
@Override
public String toString() {
return "Node{" +
"item=" + item +
'}';
}
}
➢分析HashSet的添加元素底层是如何实现 (hash() +equals())
- HashSet底层是HashMap
- 添加一个元素时,先得到hash值 会转成->索引值
- 找到存储数据表table ,看这个索引位置是否已经存放的有元素
- 如果没有,直接加入
- 如果有,调用equals比较,如果相同,就放弃添加,如果不相同,则
添加到最后 - 在Java8中,如果一条链表的元素个数到达TREEIFY THRESHOLD(默认是8),
并且table的大小>=MIN_TREEIFY_CAPACITY(默认64),
就会进行树化(红黑树)
package www.xz.set_;
import java.util.HashSet;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashSetSource {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("java");
hashSet.add("php");
hashSet.add("java");
System.out.println("hashSet=" + hashSet);
}
}
➢分析HashSet的扩容和转成红黑树机制
- HashSet底层是HashMap,第一次添加时,table 数组扩容到16,临界值
(threshold)是16*加载因子 (loadFactor)是0.75 = 12 - 如果table数组使用到了临界值12,就
会扩容到 16 * 2 = 32,新的临界值就是 32*0.75 = 24,依次类推 - 在Java8中,如果一条链表的元素个数到达TREEIFY_THRESHOLD(默认是8),
并且table的大小>=MIN_TREEIFY_CAPACITY(默认64),就
会进行树化(红黑树),否则仍然采用数组扩容机制
package www.xz.set_;
import java.util.HashSet;
import java.util.Objects;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashSetIncrement {
public static void main(String[] args) {
/*
HashSet底层是HashMap, 第一次添加时,tabLe 数组扩容到16,
临界值(threshold)是 16*加载因子(loadFactor)是0.75 = 12
如果table 数组使用到了临界值12,就会扩容到16 * 2 = 32,
新的临界值就是32 * 0.75 = 24,依次类推
*/
HashSet hashSet = new HashSet();
// for (int i = 1; i <= 100; i++) {
// hashSet.add(i);//1,2,3,4,5,...,100
// }
/*
在Java8中,如果一条链表的元素个数到达TREEIFY_THRESHOLD(默认是8),
并且tabLe的大小>= MIN_TREEIFY_CAPACITY(默认64),就会进行树化(红黑树),
否则仍然采用数组扩容机制
*/
// for (int i = 1; i <= 12; i++) {
// hashSet.add(new A(i));
// }
/*
当我们向hashset增加一个元素,-> Node ->加入table,就算是增加了一个size++
*/
for (int i = 1; i <= 7; i++) {//在 table 的某一条链表上增加了 7 个对象
hashSet.add(new A(i));
}
for (int i = 1; i <= 7; i++) {//在 table 的另一条链表上增加了 7 个对象
hashSet.add(new A(i));
}
}
}
class A {
private int n;
public A(int n) {
this.n = n;
}
@Override
public int hashCode() {
return 100;
}
}
class B {
private int n;
public B(int n) {
this.n = n;
}
@Override
public int hashCode() {
return 200;
}
}
HashSetExercise
package www.xz.set_;
import java.util.HashSet;
import java.util.Objects;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashSetExercise {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("tom", 18));
hashSet.add(new Employee("jack", 21));
hashSet.add(new Employee("tom", 18));
System.out.println(hashSet);
for (Object o : hashSet) {
System.out.println(o);
}
}
}
class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return age == employee.age && Objects.equals(name, employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
package www.xz.set_;
import java.util.HashSet;
import java.util.Objects;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class HashSetExercise01 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
MyDate myDate1 = new MyDate(2001, 2, 12);
MyDate myDate2 = new MyDate(2001, 5, 18);
MyDate myDate3 = new MyDate(2001, 2, 12);
hashSet.add(new Staff("jack", 5000, myDate1));
hashSet.add(new Staff("tom", 10000, myDate2));
hashSet.add(new Staff("jack", 5000, myDate3));
for (Object o : hashSet) {
System.out.println(o);
}
}
}
class Staff {
private String name;
private double sal;
private MyDate birthday;
public Staff(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Staff staff = (Staff) o;
return Double.compare(staff.sal, sal) == 0 && Objects.equals(name, staff.name) && Objects.equals(birthday, staff.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, sal, birthday);
}
@Override
public String toString() {
return "Staff{" +
"name='" + name + '\'' +
", sal=" + sal +
", birthday=" + birthday +
'}';
}
}
class MyDate {
private int year;
private int month;
private int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MyDate myDate = (MyDate) o;
return year == myDate.year && month == myDate.month && day == myDate.day;
}
@Override
public int hashCode() {
return Objects.hash(year, month, day);
}
@Override
public String toString() {
return "MyDate=" + year + "-" + month + "-" + day;
}
}
Set接口实现类- LinkedHashSet
LinkedHashSet的全面说明
-
LinkedHashSet是HashSet的子类
-
LinkedHashSet 底层是一个 LinkedHashMap, 底层维护了一个
数组 + 双向链表
-
LinkedHashSet 根据元素的 hashCode值来决定元素的存储位置,同时使
用链表维护元素的次序,这使得元素看起来是以插入顺序保存的。 -
LinkedHashSet不允许添重复元素
详细说明
- 在LinkedHastSet 中维护了一个hash表和双向链表
( LinkedHashSet有head和tail )
- 每一个节点有pre和next属性,这样可以形成双向链表
-
在添加一个元素时,先求hash值,再求索引,确定该元素在
hashtable的位置,然后将添加的元素加入到双向链表(如果
已经存在,不添加[原则和hashset一样])1) tail.next = newElement; //简单指定 newElement.pre = tail; tail = newEelment; 2)
- 这样的话,我们遍历LinkedHashSet也能确保插入顺序和遍历顺序一致
package www.xz.set_;
import java.util.LinkedHashSet;
import java.util.Set;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class LinkedHashSetSource {
public static void main(String[] args) {
//分析一下LinkedHashSet的底层机制
Set set = new LinkedHashSet();
set.add(new String("AA"));
set.add(456);
set.add(456);
set.add(new Customer(" 刘", 1001));
set.add(123);
set.add("XZ");
for (Object o : set) {
System.out.println(o);
}
//1. LinkedHashSet 加入顺序和取出元素/数据的顺序一致
//2. LinkedHashSet 底层维护的是一个 LinkedHashMap(是HashMap的子类)
//3. LinkedHashSet 底层结构 (数组table + 双向链表)
//4. 添加第一次时,直接将数组 table 扩容到16, 存放的结点类型是 LinkedHashMap$Entry
//5. 数组是 HashMap$Node[] 存放的元素/数据是 LinkedHashMap$Entry 类型
}
}
class Customer {
private String name;
private int num;
public Customer(String name, int num) {
this.name = name;
this.num = num;
}
@Override
public String toString() {
return "Customer{" +
"name='" + name + '\'' +
", num=" + num +
'}';
}
}
LinkedHashSetExercise
package www.xz.set_;
import java.util.LinkedHashSet;
import java.util.Objects;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class LinkedHashSetExercise {
public static void main(String[] args) {
LinkedHashSet linkedHashSet = new LinkedHashSet();
linkedHashSet.add(new Car("奥拓", 1000));
linkedHashSet.add(new Car("奥迪", 300000));
linkedHashSet.add(new Car("法拉利", 10000000));
linkedHashSet.add(new Car("奥迪", 300000));
linkedHashSet.add(new Car("保时捷", 70000000));
linkedHashSet.add(new Car("奥迪", 300000));
for (Object o : linkedHashSet) {
System.out.println(o);
}
}
}
class Car {
private String name;
private double price;
public Car(String name, double price) {
this.name = name;
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Car car = (Car) o;
return Double.compare(car.price, price) == 0 && Objects.equals(name, car.name);
}
@Override
public int hashCode() {
return Objects.hash(name, price);
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
}
Set接口实现类- TreeSet
TreeSet是有序的,并且可以指定排序规则,TreeSet的底层是TreeMap
package www.xz.set_;
import java.util.Comparator;
import java.util.TreeSet;
/**
* @author 许正
* @version 1.0
*/
@SuppressWarnings({"all"})
public class TreeSet_ {
public static void main(String[] args) {
// TreeSet treeSet = new TreeSet();//默认按字符串排序
//可使用构造器(传入比较器) 指定排序规则
TreeSet treeSet = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
//按照首字母从后往前排序
// return ((String) o2).compareTo((String) o1);
//按照字符串长度排序
return ((String) o1).length() - ((String) o2).length();
}
});
treeSet.add("jack");
treeSet.add("tom");
treeSet.add("xz");
treeSet.add("marry");
System.out.println(treeSet);
}
}