本文主要是介绍Set 接口实现类-LinkedHashSet,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
11.1 LinkedHashSet 的全面说明
LinkedHashSet 底层机制示意图
LinkedHashSetSource.java
package com.xjz.set_;import java.util.LinkedHashSet;
import java.util.Set;@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("XJZ");System.out.println("set=" + set);//解读源码//1. LinkedHashSet 加入顺序和取出元素/数据的顺序一致//2. LinkedHashSet 底层维护的是一个 LinkedHashMap//3. LinkedHashSet 底层结构(数组 table + 双向链表)//4. 添加第一次时,直接将 数组table 扩容到16,存放的结点类型是 LinkedHashMap$Entry//5. 数组是 HashMap$Node[] 存放的元素/数组是 LinkedHashMap$Entry 类型/*//继承关系是在内部类完成.static class Entry<K,V> extends HashMap.Node<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) {this.name = name;this.no = no;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getNo() {return no;}public void setNo(int no) {this.no = no;}
}
11.2 LinkedHashSet 课后练习题
LinkedHashSetExercise.java
package com.xjz.set_;import java.util.LinkedHashSet;
import java.util.Objects;@SuppressWarnings({"all"})
public class LinkedHashSetExercise {public static void main(String[] args) {LinkedHashSet linkedHashSet = new LinkedHashSet();linkedHashSet.add(new Car("五菱宏光",3000));linkedHashSet.add(new Car("宝骏",50000));linkedHashSet.add(new Car("奥迪Rs7",1900000));linkedHashSet.add(new Car("宝骏",50000));linkedHashSet.add(new Car("思域",160000));linkedHashSet.add(new Car("奥迪Rs7",1900000));System.out.println("linkedHashSet=" + linkedHashSet);}
}
/*** Car 类(属性:name,price), 如果 name 和 price 一样,* 则认为是相同元素,就不能添加。*/class Car {private String name;private double price;public Car(String name, double price) {this.name = name;this.price = price;}public String getName() {return name;}public void setName(String name) {this.name = name;}public double getPrice() {return price;}public void setPrice(double price) {this.price = price;}@Overridepublic String toString() {return "\nCar{" +"name='" + name + '\'' +", price=" + price +'}';}//重写 equals 方法 和 hashCode 方法//当 name 和 price 相同时,就返回相同的 hashCode 值,equals返回 true@Overridepublic 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);}@Overridepublic int hashCode() {return Objects.hash(name, price);}
}
这篇关于Set 接口实现类-LinkedHashSet的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!