Collections类定义了一系列用于操作集合的静态方法。
常用方法:
1.sort():排序(默认是升序排列,降序实现方法)
如果ArrayList的泛型指定为String int等类型,可以通过Arrays.sort(Object o);排序,但如果是更复杂的类的对象,则需要通过一下方法:
该类需实现Comparable接口,并重写compareTo()方法。
Students类:
package com.yh.sort;
// 实现Comparable接口
public class Students implements Comparable<Students> { private int id;
private String name; public Students() {} public Students(int id,String name) {
this.setId(id);
this.setName(name);
} public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
// 重写compareTo方法
@Override
public int compareTo(Students stu) {
// TODO Auto-generated method stub
if(this.getId()==stu.getId())
return 0;
else if(this.getId()>stu.getId())
return 1;
else
return -1;
}
}
TestStundent类:
package com.yh.sort; import java.util.ArrayList;
import java.util.Collections; public class TestStudent { public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Students> list = new ArrayList<>();
list.add(new Students(10,"stu10"));
list.add(new Students(5,"stu5"));
list.add(new Students(15,"stu15"));
Collections.sort(list);
for(int i=0;i<list.size();i++) {
System.out.println("学号:"+list.get(i).getId()+" 姓名:"+list.get(i).getName());
}
}
}
2.binarySearch():查找
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;public class Student1Test {
public static void main(String[] args) {
List<Student1> list1 = new ArrayList<Student1>();
list1.add(new Student1("林青霞", 27));
list1.add(new Student1("风清扬", 30));
list1.add(new Student1("刘晓曲", 28));
list1.add(new Student1("武鑫", 29));
list1.add(new Student1("林青霞", 27)); int index=Collections.binarySearch(list1, new Student1("林青霞", 27));
System.out.println(index);
}
}
3.max()/min():查找最大/最小值