java练习题(set集合)
package cn.Work1206.hooong01;
public class Student{
private String name;
private int Chinese;
private int English;
public Student() {
}
public Student(String name, int chinese, int english) {
this.name = name;
Chinese = chinese;
English = english;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getChinese() {
return Chinese;
}
public void setChinese(int chinese) {
Chinese = chinese;
}
public int getEnglish() {
return English;
}
public void setEnglish(int english) {
English = english;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", Chinese=" + Chinese +
", English=" + English +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (Chinese != student.Chinese) return false;
if (English != student.English) return false;
return name != null ? name.equals(student.name) : student.name == null;
}
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + Chinese;
result = 31 * result + English;
return result;
}
}
package cn.Work1206.hooong01;
import java.util.Collection;
import java.util.Comparator;
import java.util.TreeSet;
/*
在某次考试中,学生的成绩信息如下:
姓名 年龄 成绩 22 95 22 100 22 90 22 90
请分别用Comparable和Comparator两个接口对以上同学的成绩做降序排序,
如果成绩一样,那在成绩排序的基础上按照年龄由小到大排序,
成绩和年龄都一样,则按照姓名的字典顺序排序。
*/
public class Demo06 {
public static void main(String[] args) {
TreeSet<Student> students = new TreeSet<>(new Comparator<Student>() {
@Override
public int compare(Student o1, Student o2) {
int i = o1.getChinese() + o1.getEnglish() - o2.getChinese() - o2.getEnglish();
int i1 = i == 0 ? o1.getName().compareTo(o2.getName()) : i;
return i1;
}
});
students.add(new Student("Tom",20,90 ));
students.add(new Student("John",20 ,100 ));
students.add(new Student("Lily",22,100));
students.add(new Student("Lucy",22,90));
students.add(new Student("Kevin",22,90));
students.add(new Student("Jerry",22,95));
for (Student student : students) {
System.out.println(student);
}
}
}