我想對包含屬性名稱和課程的學生對象列表進行排序,以便根據名稱完成排序,如果兩個名稱相同,則應考慮排序過程。我可以單獨做,而是希望有一個單一的列表... plz幫助...如何使用java中的不同屬性對列表進行排序
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package studentlist;
import java.util.*;
/**
*
* @author Administrator
*/
public class StudentList {
/**
* @param args the command line arguments
*/
String name, course;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public StudentList(String name, String course) {
this.name = name;
this.course = course;
}
public static void main(String[] args) {
// TODO code application logic here
List<StudentList> list = new ArrayList<StudentList>();
list.add(new StudentList("Shaggy", "mca"));
list.add(new StudentList("Roger", "mba"));
list.add(new StudentList("Roger", "bba"));
list.add(new StudentList("Tommy", "ca"));
list.add(new StudentList("Tammy", "bca"));
Collections.sort(list, new NameComparator());
Iterator ir = list.iterator();
while (ir.hasNext()) {
StudentList s = (StudentList) ir.next();
System.out.println(s.name + " " + s.course);
}
System.out.println("\n\n\n ");
Collections.sort(list, new CourseComparator());
Iterator ir1 = list.iterator();
while (ir1.hasNext()) {
StudentList s = (StudentList) ir1.next();
System.out.println(s.name + " " + s.course);
}
}
}
class NameComparator implements Comparator<StudentList> {
public int compare(StudentList s1, StudentList s2) {
return s1.name.compareTo(s2.name);
}
}
class CourseComparator implements Comparator<StudentList> {
public int compare(StudentList s1, StudentList s2) {
return s1.course.compareTo(s2.course);
}
}
你已經知道條件,現在將其應用於比較級 –