Collections类应用实例:
(1)元素排序
import java.util.*;
public class text1 {
public static void ptintElements(Collection c)
{
Iterator i=c.iterator();
while(i.hasNext())
System.out.println(i.next());
}
public static void main(String[] args)
{
Student s1=new Student(1,"qy");
Student s2=new Student(2,"kng");
Student s3=new Student(3,"lk");
Student s4=new Student(4,"ji");
Student s5=new Student(5,"zhag");
Student s6=new Student(6,"nng");
ArrayList a=new ArrayList();
a.add(s1);
a.add(s2);
a.add(s3);
a.add(s4);
a.add(s5);
a.add(s6);
Collections.sort(a); //若要对对象排序,必须先实现Compare接口
text1.ptintElements(a);
}
}
class Student implements Comparable{
int num;
String name;
Student(int num,String name)
{
this.name=name;
this.num=num;
}
public int compareTo(Object o) //compare接口实现过程
{
Student s=(Student)o;
return num>s.num ? 1 :(num==s.num ? 0 : -1);
}
public String toString()
{
return num+" "+name;
}
}
补充:1.(也可用内部类实现接口的方式来实现Comparable接口,这样这个比较方法就完全属于Student这个类了)
可以在Student类中加入这样一个内部类:
static class StudentCompare implements Comparator(比较器){
public int compare(Object o1,Object o2)
{
Student s1=(Student)o1;
Student s2=(Student)o2;
return s1.num>s2.num ? 1 :(s1.num==s2.num ? 0 : -1);
}
}
在main主函数中可以这样调用:
Collections.sort(a,new Student.StudentCompare()); //a后是一个比较器;
2.当学号相同时,也可实现名字的排序(在内部类中补上如下代码)
int result=s1.num>s2.num ? 1 :(s1.num==s2.num ? 0 : -1);
if(result==0)
return s1.name.compareTo(s2.name); //String类已经实现了Comparable接口;
return result;
3.也可用Collections.sort(a,Collections.reverseOrder());比较器实现反排序;
(2)最大值、最小值、和查找同Arrays类;
Arrays类是对数组的操作,而Collections是对列表的操作;
java集合类(二)Collections类内元素排序
最新推荐文章于 2022-01-25 19:26:35 发布