HashSet和TreeSet案例区别
在学习HashSet和TreeSet过程碰到这么个情况,同样的代码形式在HashSet类中运行正常,但是换成TreeSet类后提示ClassCastException: hashset_.Employee1 cannot be cast to java.。因为初学java,也搞不懂两类之间的应用环境及相同方法的差异性。请查看下面一段代码,运行正常,但是修改成TreeSet类后就不行,请大家不吝赐教!
案例说明:旨在验证在HashSet类中可以按照某种设定,禁止添加重复元素。这里是设定员工(自定义Employee类)的姓名和生日(自定义类)分别相同的情况下,视为同一员工,禁止重复添加。
import java.util.HashSet;
import java.util.Objects;
@SuppressWarnings({"all"})
public class HashSet2 {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
hashSet.add(new Employee("tom",3000,new MyDate(1995,12,7)));
hashSet.add(new Employee("jack",2400,new MyDate(1998,17,17)));
hashSet.add(new Employee("tom",3000,new MyDate(1995,12,7)));
hashSet.add(new Employee("marry",2000,new MyDate(2002,8,20)));
System.out.println(hashSet);
}
}
class Employee{
private String name;
private double sal;
private MyDate birthday;
public Employee(String name, double sal, MyDate birthday) {
this.name = name;
this.sal = sal;
this.birthday = birthday;
}
public String getName() {
return name;
}
public double getSal() {
return sal;
}
public MyDate getBirthday() {
return birthday;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return Objects.equals(name, employee.name) && Objects.equals(birthday, employee.birthday);
}
@Override
public int hashCode() {
return Objects.hash(name, birthday);
}
@Override
public String toString() {
return "name=" + name + " sal=" + sal + " birthday=" + birthday ;
}
}
class MyDate{
private int year;
private int month;
private 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 int getMonth() {
return month;
}
public int getDay() {
return 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);
}
@Override
public String toString() {
return "MyDate{" +
"year=" + year +
", month=" + month +
", day=" + day +
'}';
}
}