2013-11-18 3 views
2

Я вычисляю общий знак каждого ученика. Затем я добавляю этот объект в массив-список. То, что я хочу сделать, основано на этой общей метке (а не на объекте объекта Student), сортирует список массивов и отображает детали учащихся с общей меткой. Я не знаю, как это сделать. Может ли кто-нибудь предложить мне хорошую оптимизацию для моей работы?Сортировка списка массивов объектов по общему значению

public static void TotalModuleMarkAboveAvg(){ 
     double totalModuleMarkAvg = OverallClassAverage(false); //getting the avg of the total marks 
     ArrayList<Student> students = new ArrayList<Student>(); 
     double studentTotalModuleMark = 0.0; 
     student = new Student(); 
     System.out.println("List of students whose total module marks fall below the class average "); 
     for(int i=0; i<MAX_STUDENT; i++){ 
      Student student = vector.get(i); 
      studentTotalModuleMark = student.getCoursework1()*20/100; 
      studentTotalModuleMark += student.getCoursework2()*20/100; 
      studentTotalModuleMark += student.getFinalExam()*60/100; 
      if(studentTotalModuleMark > totalModuleMarkAvg){ 
       students.add(student); 
      } 
    // here I want to sort my array list based on the studentTotalModuleMark and display student registration number and total module mark 
     } 

    } 

класс студент

public class Student implements java.io.Serializable{ 
    private int registrationNumber; 
    private int coursework1; 
    private int coursework2; 
    private int finalExam; 

    public int getRegistrationNumber() { 
     return registrationNumber; 
    } 
    public void setRegistrationNumber(int registrationNumber) { 
     this.registrationNumber = registrationNumber; 
    } 
    public int getCoursework1() { 
     return coursework1; 
    } 
    public void setCoursework1(int coursework1) { 
     this.coursework1 = coursework1; 
    } 
    public int getCoursework2() { 
     return coursework2; 
    } 
    public void setCoursework2(int coursework2) { 
     this.coursework2 = coursework2; 
    } 
    public int getFinalExam() { 
     return finalExam; 
    } 
    public void setFinalExam(int finalExam) { 
     this.finalExam = finalExam; 
    } 
} 
+1

Сортировка будет настоящей головной болью, не имея итоговой величины как поля. Вам понадобится соответствующий массив для хранения всего. И, сортируя Arraylist MANUALLY, сортируйте соответствующие массивы. Почему бы не иметь общее поле? –

+0

Кроме того, у меня есть ощущение, что вы хотите, чтобы ваш ArrayList размещался вне метода. Делает гораздо больше смысла. –

+1

И почему у вас в вашем методе есть две переменные студента. Не хорошая практика. –

ответ

1
public class Student implements Comparable<Student>, Serializable { 
    private int registrationNumber; 
    private int coursework1; 
    private int coursework2; 
    private int finalExam; 
    private int totalScore; 

    public Student(int registrationNumber, int coursework1, 
          int coursework2, int finalExam) { 
     this.registrationNumber = registrationNumber; 
     this.coursework1 = coursework1; 
     this.coursework2 = coursework2; 
     this.finalExam = finalExam; 
     totalScore = coursework1 + coursework2 + finalExam; 
    } 

    ... 
    // all you getters and setters 
    ... 



    public int compareTo(Student s){ 
     if (this.totalScore > s.totalScore) 
      return 1; 
     else if (this.totalScore == s.totalScore) 
      return 0; 
     else 
      return -1; 
    } 
} 

Теперь все готово для вас, чтобы использовать метод Collections.sort()

ArrayList<Student> students = new ArrayList<Student>(); 

Student student1 = new Student(1, 90, 70, 100); 
Student student1 = new Student(2, 85, 43, 90); 
Student student1 = new Student(3, 67, 70, 80); 

students.add(student1); 
students.add(student2); 
students.add(student3); 

Collections.sort(students); 
// Magic! 

Edit: Использование анонимного компаратор

public class ComparatorPractice{ 
    public static void main(String[] args){ 
     ArrayList<Student> students = new ArrayList<Student>(); 

     Student student1 = new Student(1, 90, 70, 100); 
     Student student1 = new Student(2, 85, 43, 90); 
     Student student1 = new Student(3, 67, 70, 80); 

     students.add(student1); 
     students.add(student2); 
     students.add(student3); 

     Collections.sort(students, new Comparator(){ 
      @Override 
      public int compare(Object o1, Object o2){ 
       if (o1 instanceof Student && o2 instanceof Student){ 
        if (o1.coursework1 > o2.coursework1) 
         return 1; 
        else if (o1.coursework1 == o2.coursework1) 
         return 0; 
        else 
         return -1; 
       } 
      } 
     }); 

     System.out.println("Highest coursework1 mark is " 
          + students.get(students.size()- 1).coursework1); 

     Collections.sort(students, new Comparator(){ 
      @Override 
      public int compare(Object o1, Object o2){ 
       if (o1 instanceof Student && o2 instanceof Student){ 
        if (o1.coursework2 > o2.coursework2) 
         return 1; 
        else if (o1.coursework2 == o2.coursework2) 
         return 0; 
        else 
         return -1; 
       } 
      } 
     }); 

     System.out.println("Highest coursework2 mark is " 
          + students.get(students.size()- 1).coursework2); 
    } 
} 

Просто сделайте то же самое для каждого компонента, который хотите отсортировать. Если вы сделаете это таким образом, не используя Comparable, вам не нужны compareTo() или implements Comparable в вашем классе Student.

+0

Значит много .. Высоко ценим – Eclayaz

+0

Я не уверен, как вы хотели, чтобы totalScore был рассчитан, так что просто сделайте расчет самостоятельно. –

+1

yah sure, этого более чем достаточно !! – Eclayaz

Смежные вопросы