定义一个学生类Student,成员变量包括:姓名,生日,学号,学校;重写方法toString,equals,hashCode;实现接口Comparable,按照学号大小进行比较;定义构造方法。 代码形式如下: public class Main{ public stat
时间: 2023-07-28 17:09:43 浏览: 119
ic void main(String[] args) {
Student s1 = new Student("Tom", "2000-01-01", "001", "ABC School");
Student s2 = new Student("Jerry", "1999-12-31", "002", "DEF School");
Student s3 = new Student("Lucy", "2000-02-14", "003", "GHI School");
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 s3: " + s1.equals(s3));
System.out.println("s1 hashCode: " + s1.hashCode());
System.out.println("s2 hashCode: " + s2.hashCode());
System.out.println("s3 hashCode: " + s3.hashCode());
System.out.println("s1 compare s2: " + s1.compareTo(s2));
System.out.println("s1 compare s3: " + s1.compareTo(s3));
System.out.println("s2 compare s3: " + s2.compareTo(s3));
}
public static class Student implements Comparable<Student> {
String name;
String birthday;
String id;
String school;
public Student(String name, String birthday, String id, String school) {
this.name = name;
this.birthday = birthday;
this.id = id;
this.school = school;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", birthday='" + birthday + '\'' +
", id='" + id + '\'' +
", school='" + school + '\'' +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(id, student.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public int compareTo(Student o) {
return this.id.compareTo(o.id);
}
}
}
阅读全文