5.Set
- 无序
- 无索引 不能用索引方式遍历
- 不能重复
以HashSet为例讲解
5.1 Set
public class Set01 {
public static void main(String[] args) {
Set set=new HashSet();
set.add("孙悟空");
set.add("猪八戒");
set.add("沙悟净");
set.add("猪八戒");
set.add(null);
System.out.println(set);
}
}
1.Set接口对象不能存放重复元素 可以添加一个null
2.Set接口对象存放数据是无序的,即添加顺序与取出顺序不一致,但是每次取出顺序一致,不能通过索引遍历
3.Set可以添加两个相同的对象
Set set1=new HashSet();
set1.add(new Dog("Lucy"));
set1.add(new Dog("Jack"));
set1.add(new Dog("Lucy"));
System.out.println("set1="+set1);
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-5rcAzizR-1659801328022)(https://s2.loli.net/2022/08/06/E7xVe95I2jFwuUD.png)]
Set set2=new HashSet();
set2.add(new String("aa"));
set2.add(new String("aa"));
System.out.println("set2="+set2);
5.2 HashSet
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cLi8zcQv-1659801328025)(https://s2.loli.net/2022/08/06/bylL7dUawcIVKWN.png)]
public class Set02_HashSetSource {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add("java");
hashSet.add("PHP");
hashSet.add("python");
System.out.println("hashSet="+hashSet);
}
}
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FzkOFksj-1659801328027)(img/image-20220805095000009.png)]
* final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
* //if语句表示如果table为空 或者大小为0,就第一次扩容到16个空间
//table就是hashMap的一个数组
if ((tab = table) == null || (n = tab.length) == 0) //定义辅助变量
n = (tab = resize()).length;
//1,根据key得到的哈希值计算该key应该存放在table那个位置
//并且把这个位置的对象赋值给p
//2、判断p是否为空
// 2.1.若p为空表示还没有存放元素,就创建一个Node(key="java",value=PERASET)
// 2.2 就放在该位置 tab[i]=newNode(hash,key,value,null)
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
/* //如果当前索引位置链表对应的第一个位置和准备添加的key和hash一样
* 并且满足下面条件之一:
* (1) 准备加入的key和p 相同的Node结点的key是同一个对象
* (2) p相同的Node结点的key的equals()和准备加入的key比较后相同
*/
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
//判断p是不是红黑树
//如果是红黑树就用下面方法添加
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
* // 如果table队对应的索引位置已经是一个链表,就用for循环比较
* //(1)依次和链表的每一个元素比较后都不相同,则加入到该链表的最后
* //(2)在依次比较过程中,如果有相同的情况,就break
* // 注意:在把元素添加到链表后,立即判断该立案表是否达到8个节点
* //如果达到就对党建链表树华(转成红黑树),在进行树化时,还进行判断 如果该table数组的大小<64,不会马上树好
else {//如果table对应索引位置已经是一个链表,就用for循环比较
* //(1)依次和该链表每一个元素比较后,都不相同,则加入到该链表的最后
* //(2)依次和该链表每一个元素比较过程中,如果有相同情况,直接break
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
1.HashSet底层是HashMap,第一次添加时,table数组扩容到16,临界值(threshold)是16加载因子
(loadFactor)是0.75 = 12
2.如果table数组使用到了临界值12,就会扩容到16=32,新的临界值就是32*0.75 = 24,依次类推
3.在Java8中,如果一条链表的元素个数到达 TREEIFY_THRESHOLD(默认是8),并且table的大小>=MIN TREEIFY CAPACITY(默认64),就会进行树化(红黑树),否则仍然采用数组扩容机制
5.3 HashSet 练习
public class Set04_HashSetExcesice {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("张三",27));
hashSet.add(new Employee("李四",23));
hashSet.add(new Employee("张三",27));
System.out.println(hashSet);
}
}
class Employee{
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
// 如果那么和age相同,返回相同的hashcode
@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 && name.equals(employee.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-8fAEVVEc-1659801328043)(https://s2.loli.net/2022/08/06/gUxPFvwLK8W5QDl.png)]
package set.HashSet;
import java.util.HashSet;
import java.util.Objects;
/**
* @Author HSL
* @Date 2022-08-06 0006 15:42
* QQ: 1365343049
*/
public class Set04_HashSetExcesice02 {
public static void main(String[] args) {
Employee1 employee1 = new Employee1("张三", "23", new MyDate(2000, 1, 3));
Employee1 employee2 = new Employee1("张三", "555", new MyDate(2000, 1, 3));
HashSet hashSet = new HashSet();
hashSet.add(employee1);
hashSet.add(employee2);
System.out.println(hashSet);
}
}
class MyDate{
int year;
int month;
int day;
public MyDate(int year, int month, int day) {
this.year = year;
this.month = month;
this.day = day;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public int getMonth() {
return month;
}
public void setMonth(int month) {
this.month = month;
}
public int getDay() {
return day;
}
public void setDay(int day) {
this.day = day;
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", 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);
}
}
class Employee1{
private String name;
private String sal;
private MyDate birthday;
@Override
public String toString() {
return "Employee1{" +
"name='" + name + '\'' +
", sal='" + sal + '\'' +
", birthday=" + birthday.toString() +
'}';
}
public Employee1(String name, String sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSal() {
return sal;
}
public void setSal(String sal) {
this.sal = sal;
}
public MyDate getBirthday() {
return birthday;
}
public void setBirthday(MyDate birthday) {
this.birthday = birthday;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee1 employee1 = (Employee1) o;
return name.equals(employee1.name) && birthday.equals(employee1.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, birthday);
}
}
5.4 LinkedHashSet
- LinkedHashSet是HashSet的子类
- LinkedHashSet的底层是一个LinkedHashMap。底层维护了数组+双向链表
- LinkedHashSet根据元素HashCode值决定元素存储位置,同时使用链表维护元素次序
- LinkedHashSet不允许添加重复元素
public class Set06_LinkedHashsetSource {
public static void main(String[] args) {
// 分析LinkedHashSet底层机制
// LinkedHashSet加入和取出顺序一致
// LinkedHashSet底层维护的是LinkedHashMap
// LinkedHashSet底层结构(数组table+双向链表)
// 添加第一次时,直接将数组table扩容到16,存放的节点是LinkedHashMapEntry
// 数组是HashMapNode[]存放的元素是LinkedHashMapEntry
LinkedHashSet set = new LinkedHashSet();
set.add(456);
set.add(456);
set.add(789);
set.add(new Costmer("胡",22));
set.add(123);
System.out.println(set);
/* LinkedHashSet加入顺序和去除顺序一致
* */
}
}
class Costmer{
private String name;
private int age;
public Costmer(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Costmer{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}