package enumeration;
import java.util.HashSet;
import java.util.Objects;
public class HashSet_ {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
Employee milan = new Employee("milan", 12500, new Employee.MyDate(2021, 11, 20));
Employee jack = new Employee("jack", 12500, new Employee.MyDate(2021, 11, 20));
Employee tom = new Employee("milan", 12500, new Employee.MyDate(2021, 11, 20));
hashSet.add(milan);
hashSet.add(jack);
hashSet.add(tom);
System.out.println("hashSet.size = " +hashSet.size());
System.out.println("hashSet = " + hashSet );
//重写他们的hashCode,如果name 和Age一样就放回相同的hashCode
// System.out.println(hashSet);
}
}
class Employee{
private String name;
private double sal;
private MyDate myDate;
@Override
public String toString() {
return "Employee{" +
"name='" + name + '\'' +
", sal=" + sal +
", myDate=" + myDate +
'}';
}
public Employee(String name, double sal, MyDate myDate) {
this.name = name;
this.sal = sal;
this.myDate = myDate;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Double.compare(employee.sal, sal) == 0 &&
Objects.equals(name, employee.name) &&
Objects.equals(myDate, employee.myDate);
}
@Override
public int hashCode() {
return Objects.hash(name, sal, myDate);
}
static 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;
}
@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);
}
}
}
内部类、HashSet
最新推荐文章于 2024-11-09 14:56:57 发布
此代码示例展示了如何在 Java 中使用 HashSet,并重写 Employee 类及其内部类 MyDate 的 equals 和 hashCode 方法,确保当对象属性相同时,HashSet 能正确处理重复项。程序输出了 HashSet 的大小和内容,演示了 equals 和 hashCode 方法在集合操作中的作用。
1848

被折叠的 条评论
为什么被折叠?



