/**
* 题目分数:8分
* 建议时间:15分钟
* 题目要求:写一个Student类有姓名,年龄和学号三个属性
a.在创建对象时给这些属性进行初始化
b.将学生的相关信息(姓名,年龄,学号)存入到合适的集合中,并且根据学生年龄按降序打印到控制台上
*/
public static void main(String[] args) {
Student s1 = new Student("cgx",100,"nb001");
Student s2 = new Student("lzr",50,"yb002");
Student s3 = new Student("jty",5000,"nbnb001");
//创建一个TreeSet集合,传入比较器,按照年龄来进行降序排序
TreeSet<Student> ts = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
//o1是即将存入集合的元素,如果这个元素比较小,就返回正数,存到右边,也就是小的存到了后面,这样就是降序
int num = o2.getAge() - o1.getAge();
return num == 0 ? 1 : num;
}
});
ts.add(s1);
ts.add(s2);
ts.add(s3);
System.out.println(ts);
}
}
class Student {
private String name;
private int age;
private String id;
public Student(String name, int age, String id) {
super();
this.name = name;
this.age = age;
this.id = id;
}
public Student() {
super();
// TODO Auto-generated constructor stub
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@Override
public String toString() {
return "Student [name=" + name + ", age=" + age + ", id=" + id + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + age;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Student other = (Student) obj;
if (age != other.age)
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}