複製代碼代碼如下:
導入java.util.arraylist;
導入java.util.collections;
導入java.util.comparator;
導入java.util.list;
公共類比較最終實施比較器<Stuentity> {
/**
* @param args
*/
公共靜態void main(string [] args){
list <Stuentity> list = new ArrayList <Stuentity>();
Stuentity stud1 = new Stuentity();
Stud1.Setage(10);
Stud1.setName(“ ABC”);
Stuentity stud2 = new Stuentity();
stud2.setage(10);
Stud2.setName(“ BDC”);
Stuentity Stud3 = new Stuentity();
Stud3.Setage(5);
Stud3.setName(“ BDD”);
Stuentity stud4 = new Stuentity();
Stud4.setage(30);
Stud4.setName(“ AAD”);
list.Add(Stud1);
list.Add(Stud2);
list.Add(Stud3);
list.Add(Stud4);
collections.sort(list,new comparatortest());
for(Stuentity Stud:list){
system.out.println(stud.getage()+“:”+stud.getName());
}
}
/**
*
*/
@Override
公共int比較(Stuentity Stud1,Stuentity Stud2){
//根據姓名排序
int maxName = stud1.getName()。
如果(maxName!= 0)
返回maxName;
//根據年齡排序
int maxage = stud1.getage() - stud2.getage();
// if(maxage!= 0)
返回maxage;
}
}
輸出:
複製代碼代碼如下:
30:AAD
10:ABC
10:BDC
5:BDD
java的比較器很有用,實現比較接口的(比較(),然後調用,然後調用collections.sort(list,new comparatortest());就可以將列表進行排序,很方便,很方便
使用時要注意(比較()方法中的返回,優先的排序規則要寫在前面,優先的排序規則要寫在前面
實體類:
複製代碼代碼如下:
/**
*學生實體類
*
*/
公共班級的結實{
私人int StudentId; //學號
私有字符串名稱;
私人int年齡;
私人弦性; //性別
私人int roomnumber; //房間號
私人字符串學位; //學位
私人int等級; //年級
私人字符串deviceNumber; //設備號
私人int groupnumber; //所屬的小組
私人墨西哥javascore; // Java成績
私有int netScore; // net成績
公共字符串getDegree(){
返回學位;
}
public void setDegree(字符串度){
this.degree =度;
}
public int getGrade(){
退貨等級;
}
公共void setgrade(int等級){
this.grade =等級;
}
/**
*初始化有參構造函數
*
* @param ID
* @param名稱
* @param年齡
* @param性
* @param roomnumber
* @param deviceNumber
* @Param GroupNumber
* @param javascore
* @Param NetScore
*/
公共成立(字符串名稱,int age,string sex,int roomnumber,
字符串deviceNumber,int groupNumber,int javascore,int netScore){
this.name = name;
this.age = age;
this.sex =性別;
this.Roomnumber = Roomnumber;
this.deviceNumber = deviceNumber;
this.groupnumber = groupNumber;
this.javascore = Javascore;
this.netscore = netScore;
}
/**
*無參構造函數
*/
公共結構(){
}
public int getjavascore(){
返回爪哇山脈;
}
公共Void Setjavascore(INT Javascore){
this.javascore = Javascore;
}
public int int getnetscore(){
返回netScore;
}
public void setnetscore(int netScore){
this.netscore = netScore;
}
public int int getstudentid(){
返回StudentId;
}
public void setstudentid(int studentId){
this.studentid = studentId;
}
公共字符串getName(){
返回名稱;
}
public void setName(字符串名稱){
this.name = name;
}
public int getage(){
返回年齡;
}
公共空隙套裝(int age){
this.age = age;
}
public String getSex(){
返回性
}
public void setSex(string sex){
this.sex =性別;
}
public int getroomnumber(){
返回室內;
}
public void setroomnumber(int roomnumber){
this.Roomnumber = Roomnumber;
}
public String getDeviceNumber(){
返回DeviceNumber;
}
public void setDeviceNumber(字符串deviceNumber){
this.deviceNumber = deviceNumber;
}
public int int getGroupnumber(){
返回groupnumber;
}
public void setGroupnumber(int groupNumber){
this.groupnumber = groupNumber;
}
}