✈【【零基础 快速学Java】韩顺平 零基础30天学会Java】
【韩老师的LinkedHashSet底层机制示意图】
【举个栗子】
package com.dingjiaxiong.set_;
import java.util.LinkedHashSet;
import java.util.Objects;
/**
* ClassName: LinkedHashSetExercise
* date: 2022/9/5 19:50
*
* @author DingJiaxiong
*/
@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)); //不行
System.out.println("linkedHashSet = " + linkedHashSet);
}
}
class Car{ //如果name和price一样,则认为是相同元素,不能添加
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;
}
@Override
public String toString() {
return "Car{" +
"name='" + name + '\'' +
", price=" + price +
'}';
}
//重写equals 和 hashcode 方法
@Override
public boolean equals(Object obj) {
if (this == obj){
return true;
}
if (obj == null || getClass() != obj.getClass()){
return false;
}
Car car = (Car) obj;
return Double.compare(car.price,price) == 0 && Objects.equals(name,car.name);
}
@Override
public int hashCode() {
return Objects.hash(name,price);
}
}
运行结果