LinkedHashSet的全面说明
1、LinkedHashSet是HashSet的子类
2、LinkedHashSet底层是一个LinkedHashMap,底层维护了一个数组+双向链表
3、LinkedHashSet根据元素的hashCode值来决定元素的存储位置,同时使用链表维护元素的次序,这使得元素看起来是以插入顺序保存的
4、LinkedHashSet不允许添加重复元素
说明:
1、在LinkedHastSet中维护了一个hash表和双向链表(LinkedHashSet有head和tail)
2、每一个节点有before和after属性,这样可以形成双向链表
3)、在添加一个元素时,先求hash值,在求索引 ,确定该元素在hashtable的位置,然后将添加的元素加入到双向链表(如果已经存在,不添加【原则 和hashset一样】)
= newElement //简单指定
= tail
tail = newElement
4、这样的话,我们遍历 LinkedHashSet也能确保插入顺序和遍历顺序一致
import ;
import ;
public class LinkedHashSetSource {
public static void main(String[] args) {
//分析一下LinkedHashSet的底层机制
Set set = new LinkedHashSet();
(new String("AA"));
(456);
(456);
(new Customer("刘",1001));
(123);
("HSP");
("set = "+ set);
//解读
/*
加入顺序和取出元素/数据的顺序一致
底层维护的是一个LinkedHashMap(是HashMap的子类)
底层结构(数组table+双向链表)
4.添加第一次时,直接将数组table扩容到16,存放的结点类型是 LinkedHashMap$Entry
5.数组是HashMap$Node[]存放的元素/数据是LinkedHashMap$Entry类型
//继承关系是在内部完成的。
static class Entry<K,V> extends <K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
*/
}
}
class Customer{
private String name;
private int no;
public Customer(String name, int no) {
= name;
= no;
}
}
练习
Car类(属性:name,price),如果name和price一样,则认为是相同元素,就不能添加
import ;
import ;
public class LinkedHashSetExercise01 {
public static void main(String[] args) {
LinkedHashSet linkedHashSet = new LinkedHashSet();
(new Car("奥拓",1000));
(new Car("奥迪",30000));
(new Car("法拉利",1000));
(new Car("宝马",1000));
(new Car("奥迪",30000));
(linkedHashSet);
}
}
class Car{
private String name;
private double price;
//重写equals方法和hashCode
//当name和price相同时,就返回相同的hashCode值,equals返回T
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != ()) return false;
Car car = (Car) o;
return (, price) == 0 && (name, );
}
@Override
public int hashCode() {
return (name, price);
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
public Car(String name, double price) {
= name;
= price;
}
}