试编写一个教师类,教师有姓名、年龄、工资等属性,如果两个教师姓名、年龄和工资都相同,就认为是同一人,不能加入同一个集合,试用TreeSet类将若干教师信息保存并显示。
时间: 2024-01-18 13:02:34 浏览: 216
好的,以下是一个简单的教师类的示例代码:
```java
import java.util.Objects;
public class Teacher implements Comparable<Teacher> {
private String name;
private int age;
private double salary;
public Teacher(String name, int age, double salary) {
this.name = name;
this.age = age;
this.salary = salary;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public double getSalary() {
return salary;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Teacher teacher = (Teacher) o;
return age == teacher.age &&
Double.compare(teacher.salary, salary) == 0 &&
Objects.equals(name, teacher.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age, salary);
}
@Override
public int compareTo(Teacher o) {
if (this.equals(o)) {
return 0;
}
int result = this.name.compareTo(o.getName());
if (result == 0) {
result = Integer.compare(this.age, o.getAge());
}
if (result == 0) {
result = Double.compare(this.salary, o.getSalary());
}
return result;
}
@Override
public String toString() {
return "Teacher{" +
"name='" + name + '\'' +
", age=" + age +
", salary=" + salary +
'}';
}
}
```
在这个示例中,教师类Teacher实现了Comparable接口,重写了equals()、hashCode()和compareTo()方法。其中,equals()和hashCode()方法用于判断两个教师对象是否相等;compareTo()方法用于将教师对象按照姓名、年龄、工资的顺序比较大小,以便于TreeSet类进行排序和去重。
下面是一个使用TreeSet类保存教师信息的示例代码:
```java
import java.util.TreeSet;
public class TeacherTest {
public static void main(String[] args) {
TreeSet<Teacher> teacherSet = new TreeSet<>();
Teacher teacher1 = new Teacher("Tom", 35, 5000);
Teacher teacher2 = new Teacher("Jerry", 30, 4000);
Teacher teacher3 = new Teacher("Tom", 35, 5000);
Teacher teacher4 = new Teacher("Lucy", 28, 4500);
Teacher teacher5 = new Teacher("Jerry", 35, 5000);
teacherSet.add(teacher1);
teacherSet.add(teacher2);
teacherSet.add(teacher3);
teacherSet.add(teacher4);
teacherSet.add(teacher5);
for (Teacher teacher : teacherSet) {
System.out.println(teacher);
}
}
}
```
在这个示例中,我们创建了一个TreeSet<Teacher>对象teacherSet,然后向其中添加了五个教师对象。由于teacher1和teacher3、teacher2和teacher5具有相同的姓名、年龄和工资,因此它们会被TreeSet类自动去重。最后,我们使用for循环遍历teacherSet中的所有教师对象,并通过toString()方法输出它们的信息。
阅读全文