import java.util.*;
import java.util.Collections;
//自定义的类需要定义含参构造方法,实现接口Compareable和重写方法comareTo方法,重新定义比较标准,并且将对象存进容器中,要重写toString方法
class Student implements Comparable{//这里实现Comparable接口,是重写其中compareTo方法重新定义比较标准
private int num;
private String name;
public Student(int num,String name)//这里构造函数实现初始化
{
this.num=num;
this.name=name;
}
public String toString(){//重写toString,输出Student类的对象内容
return num+" "+name;
}
public int compareTo(Object o)//重新定义比较标准
{
Student s=(Student)o;//将父类对象强制转化为子类对象,传给子类对象s,然后调用子类特有的属性和方法
return this.num-s.num;//相等返回0,大于返回正数,小于返回负数
}
}
public class Test1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList a=new ArrayList();
//使用add方法添加对象到ArrayList中,这里添加的是Student类的对象
a.add(new Student(90,"小明"));
a.add(new Student(80,"小刚"));
a.add(new Student(100,"小李"));
Collections.sort(a);//Collections中含有排序方法,且该类为静态类可以直接调用,参数为Arraylist对象
System.out.println(a);
}
}
Java一步一脚—ArrayList使用
最新推荐文章于 2023-07-22 10:58:33 发布