试编写一个教师类,教师有姓名、年龄、工资等属性,如果两个教师姓名、年龄和工资都相同,就认为是同一人,不能加入同一个集合,试用TreeSet类将若干教师信息保存并显示。JAVA代码实现加注释
时间: 2024-01-18 18:02:34 浏览: 62
好的,以下是实现教师类并使用TreeSet保存并显示的JAVA代码:
```java
import java.util.TreeSet;
//自定义教师类
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;
}
//按照姓名、年龄、工资的顺序比较
@Override
public int compareTo(Teacher o) {
int result = this.name.compareTo(o.name);
if(result == 0){
result = this.age - o.age;
if(result == 0){
result = (int)(this.salary - o.salary);
}
}
return result;
}
//重写equals方法,判断两个教师是否相同
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Teacher other = (Teacher) obj;
if (age != other.age)
return false;
if (Double.doubleToLongBits(salary) != Double.doubleToLongBits(other.salary))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
//重写hashCode方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
long temp;
temp = Double.doubleToLongBits(salary);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
//重写toString方法,方便输出
@Override
public String toString() {
return "Teacher [name=" + name + ", age=" + age + ", salary=" + salary + "]";
}
}
public class TeacherTest {
public static void main(String[] args) {
//创建一个TreeSet对象
TreeSet<Teacher> teachers = new TreeSet<>();
//添加教师信息
teachers.add(new Teacher("Tom", 35, 8000));
teachers.add(new Teacher("Jerry", 28, 6000));
teachers.add(new Teacher("Tom", 35, 8000)); //添加重复的教师信息
teachers.add(new Teacher("Kevin", 42, 12000));
//输出所有教师信息
for(Teacher t : teachers){
System.out.println(t);
}
}
}
```
在程序中,实现了教师类Teacher,其中包含了姓名、年龄、工资等属性。为了保证集合中不会出现重复的教师信息,重写了equals方法和hashCode方法,判断两个教师是否相同。使用TreeSet进行存储教师信息,并按照姓名、年龄、工资的顺序比较并排序,最终输出所有教师信息。
阅读全文