zl程序教程

您现在的位置是:首页 >  后端

当前栏目

java的arraylist排序示例(arraylist用法)

JAVA排序 示例 用法 ArrayList
2023-06-13 09:15:20 时间

写了一个java数组排序示例,这里分享给大家共同学习

复制代码代码如下:

packagecom.yonyou.test;
importjava.util.ArrayList;
importjava.util.Collections;
importjava.util.Comparator;
importjava.util.List;
publicclassTest{
 publicstaticvoidmain(String[]args){
  Studentzlj=newStudent("丁晓宇",21);
  Studentdxy=newStudent("赵四",22);
  Studentcjc=newStudent("张三",11);
  Studentlgc=newStudent("刘武",19);
  List<Student>studentList=newArrayList<Student>();
  studentList.add(zlj);
  studentList.add(dxy);
  studentList.add(cjc);
  studentList.add(lgc);
  System.out.println("按照年?排序:");
  Collections.sort(studentList,newSortByAge());
  for(Studentstudent:studentList){
   System.out.println(student.getName()+"/"+student.getAge());
  }
  System.out.println("=========");
  System.out.println("按照姓名排序");
  Collections.sort(studentList,newSortByName());
  for(Studentstudent:studentList){
   System.out.println(student.getName()+"/"+student.getAge());
  }
 }
}
classSortByAgeimplementsComparator{
 publicintcompare(Objecto1,Objecto2){
  Students1=(Student)o1;
  Students2=(Student)o2;
  if(s1.getAge()>s2.getAge())
   return1;
  elseif(s1.getAge()==s2.getAge()){
   return0;
  }
  return-1;
 }
}
classSortByNameimplementsComparator{
 publicintcompare(Objecto1,Objecto2){
  Students1=(Student)o1;
  Students2=(Student)o2;
  if(s1.getName().compareTo(s2.getName())<0)
   return-1;
  elseif(s1.getName().compareTo(s2.getName())>0){
   return1;
  }
  return0;
 }
}
classStudent{
 privateintage;
 privateStringname;
 publicintgetAge(){
  returnage;
 }
 publicvoidsetAge(intage){
  this.age=age;
 }
 publicStringgetName(){
  returnname;
 }
 publicvoidsetName(Stringname){
  this.name=name;
 }
 publicStudent(Stringname,intage){
  this.age=age;
  this.name=name;
 }
}