java写,定义一个学生类Student,成员变量包括:姓名,生日,学号,学校;重写方法toString,equals,hashCode;实现接口Comparable,按照学号大小进行比较;定义构造方法。 代码形式如下: public class Main{ public stat
时间: 2023-07-28 17:09:43 浏览: 422
ic void main(String[] args) {
// 创建学生对象
Student s1 = new Student("John", "1999-01-01", "20190101", "ABC School");
Student s2 = new Student("Mary", "2000-02-02", "20190202", "DEF School");
Student s3 = new Student("Tom", "2001-03-03", "20190303", "GHI School");
// 调用toString方法
System.out.println(s1.toString());
System.out.println(s2.toString());
System.out.println(s3.toString());
// 判断两个学生是否相等
System.out.println("s1 equals s2: " + s1.equals(s2));
System.out.println("s1 equals s1: " + s1.equals(s1));
// 计算学生的哈希码
System.out.println("s1 hashCode: " + s1.hashCode());
System.out.println("s2 hashCode: " + s2.hashCode());
System.out.println("s3 hashCode: " + s3.hashCode());
// 按照学号排序
Student[] students = {s2, s3, s1};
Arrays.sort(students);
for (Student student : students) {
System.out.println(student);
}
}
}
class Student implements Comparable<Student> {
private String name; // 姓名
private String birthday; // 生日
private String number; // 学号
private String school; // 学校
// 构造方法
public Student(String name, String birthday, String number, String school) {
this.name = name;
this.birthday = birthday;
this.number = number;
this.school = school;
}
// 重写toString方法
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", birthday='" + birthday + '\'' +
", number='" + number + '\'' +
", school='" + school + '\'' +
'}';
}
// 重写equals方法
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Student student = (Student) obj;
return Objects.equals(number, student.number);
}
// 重写hashCode方法
@Override
public int hashCode() {
return Objects.hash(number);
}
// 实现Comparable接口
@Override
public int compareTo(Student o) {
return this.number.compareTo(o.number);
}
}
阅读全文