实施Comparable
和排序/操作您的Collection
.
例如在您的主要代码中:
Student bad = new Student("bad");
bad.setMarks(2);
Student meh = new Student("meh");
meh.setMarks(5);
Student good = new Student("good");
good.setMarks(10);
Student otherGood = new Student("otherGood");
otherGood.setMarks(10);
// initializes a Set of students
Set<Student> students = new HashSet<Student>();
// adds the students
students.add(meh);
students.add(bad);
students.add(good);
students.add(otherGood);
// prints the "best student"
System.out.println(Collections.max(students).getName());
// initializing Set of best students
List<Student> bestStudents = new ArrayList<Student>();
// finding best mark
int bestMark = Collections.max(students).getMarks();
// adding to best students if has best mark
for (Student s: students) {
if (s.getMarks() == bestMark) {
bestStudents.add(s);
}
}
// printing best students
for (Student s: bestStudents) {
System.out.println(s.getName());
}
输出:
good
good
otherGood
...这是您Student
班级的草稿:
public class Student implements Comparable<Student> {
// we use encapsulation and set the fields' access to private
private String name;
private int age;
private int marks;
// we use encapsulation and have setters/getters/constructor access for the private fields
public Student(String name) {
this.name = name;
}
public String getName() {
return name;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
// TODO other setters/getters
// here we implement the compareTo method and decide which int to return according to the "marks" field
@Override
public int compareTo(Student otherStudent) {
if (marks < otherStudent.getMarks()) {
return -1;
}
else if (marks > otherStudent.getMarks()) {
return 1;
}
else {
return 0;
}
}
您可能还想仔细查看该接口的文档。Comparable