gpt4 book ai didi

java - 返回 Hashset 中具有最高值的类对象

转载 作者:行者123 更新时间:2023-11-29 07:07:45 25 4
gpt4 key购买 nike

我有 HashSet,其中包含对象列表,如学生、教授和系。它需要检查哪个学生得分最高,哪个教授的学生得分最高。示例代码表示类似

  class Student{
public String Name;
public int Age;
public int TotalMarks;
}
class Professor{
public String Name;
public int Age;
public Student Student_Assigned;
}

class Department{
Set<Professor> collectionDept = new HashSet<Professor>();

public Student getStudentWithHigestMarks(){
return null;
}
}

我如何使用 java 找到它?

最佳答案

实现 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;
}
}

您可能还想仔细看看 documentation对于 Comparable 接口(interface)。

关于java - 返回 Hashset 中具有最高值的类对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17899783/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com