无序ArrayList列表的排序
List集合使用Collections.sort()函数的排序
介绍List的实现类ArrayList(无序集合)的排序,它的排序方式有很多我
现在只是使用一种方式来排序。
**需要使用的类以及接口和方法**
-
工具类Collections
Collections类是Java中util工具包中的一个工具使用类,其中函数的是
静态的类名直接调用就ok -
接口类Comparable和compareTo()函数
该接口对实现它的每个类的对象强加一个整体排序。 这个排序被称为类的自然排序 ,类的compareTo方法被称为其自然比较方法 。 -
工具类Collections的函数sort()
sort(List list) :单个参数的函数排序。sort(List list, Comparator<? super T> c) :
根据指定的比较器引起的顺序对指定的列表进行排序。这个函数是有作用于对List列表的排序。
实现代码
现在开始编写一个学生类和一个测试类
学生类
/**
* Student学生类
* 实现接口implements Comparable
* */
public class Student implements Comparable {
//类的属性
private Integer stid;
private String name;
private Integer age;
//get和set方法可以写也可以不写个人习惯
public Integer getStid() {
return stid;
}
public void setStid(Integer stid) {
this.stid = stid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "Student [stid=" + stid + ", name=" + name + ", age=" + age + "]";
}
public Student(Integer stid, String name, Integer age) {
this.stid = stid;
this.name = name;
this.age = age;
}
//实现Comparable接口的函数compareTo
@Override
public int compareTo(Object o) {
//简单的说下这里相当于两个类在做判断比较 this是指的是当前的类 二下面中stu是接收到的学生类
Student stu = (Student) o;
int i = this.getStid().compareTo(stu.getStid());
//这个函数返回的值是零或正返回的-1一个,0,或1。介意去看源码
return (i != 0 ? i : this.getStid().compareTo(stu.getStid()));
}
}
测试类
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* 学生类Student 排序的测试类
* */
public class StudentTest {
public static void main(String[] args) {
Student stu1=new Student(1,"make1",23);
Student stu2=new Student(2,"make2",24);
Student stu3=new Student(3,"make3",25);
Student stu4=new Student(4,"make4",26);
List<Student> list=new ArrayList<Student>();
list.add(stu4);
list.add(stu1);
list.add(stu2);
list.add(stu3);
//没有排序
for (Student student : list) {
System.out.println(student);
}
System.out.println("---------------------------------------------");
//使用sort函数排序
Collections.sort(list);
for (Student student : list) {
System.out.println(student);
}
}
}
## 测试结果
Student [stid=4, name=make4, age=26]
Student [stid=1, name=make1, age=23]
Student [stid=2, name=make2, age=24]
Student [stid=3, name=make3, age=25]
---------------------------------------------
Student [stid=1, name=make1, age=23]
Student [stid=2, name=make2, age=24]
Student [stid=3, name=make3, age=25]
Student [stid=4, name=make4, age=26]
** 编写完毕,我是爱看星星的喵,谢谢大家的支持。**