Collections类定义了一系列用于操作集合的静态方法
Collections和Collection不同,前者是集合的操作类,后者是集合接口
Collections提供的常用静态方法
sort():排序
binarySearch():查找
max()\min():查找最大\最小值
reverse():反转元素顺序
代码演示
* @Description//Collections的常用方法
*/
public class CollectionsUseDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("ant");
list.add("bear");
list.add("pen");
list.add("zoo");
list.add("apple");
list.add("candy");
list.add("zookeeper");
System.out.println("*************");
for (String s : list) {
System.out.println(s);
}
System.out.println("**************");
Collections.sort(list);
for (String s : list) {
System.out.println(s);
}
//查找集合元素的最大、最小值
System.out.println("集合中的最大元素:" + Collections.max(list));
System.out.println("集合中的最小元素:" + Collections.min(list));
System.out.println("***************");
//查找集合中的特定元素
System.out.println(Collections.binarySearch(list, "candy"));
//反转集合元素的顺序
Collections.reverse(list);
for (String s : list) {
System.out.println(s);
}
}
}

Collections类可以对集合进行排序、查找和替换操作
实现一个类的对象之间比较大小
该类要实现Comparable接口
重写compareTo()方法,自定义比较规则
代码演示
* @Description//学生类型:学号、姓名和性别
*/
public class Student implements Comparable {
private int no;
private String sex;
private String name;
public Student() {
}
public Student(int no, String name, String sex) {
this.no = no;
this.sex = sex;
this.name = name;
}
public int getNo() {
return no;
}
public void setNo(int no) {
this.no = no;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
//重写方法:定义学生对象的比较规则
//比较规则:按学号比,学号大的同学往后排,学号小的同学往前排
//比较对象:当前学生对象(this)和Object o
@Override
public int compareTo(Object o) {
Student student = (Student) o;
if (this.no == student.no) {
return 0;//学号相同,两个学生对象一般大
} else if (this.no > student.no) {
return 1;//当前学生对象学号大于比较的学生对象学号
} else {
return -1;//当前学生对象学号小于比较的学生对象学号
}
}
}
* @Description//Collections的排序
*/
public class CollectionsUseDemo {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student stu1 = new Student(1, "张三", "男");
Student stu2 = new Student(7, "李四", "男");
Student stu3 = new Student(3, "王小花", "女");
Student stu4 = new Student(9, "王五", "男");
list.add(stu1);
list.add(stu2);
list.add(stu3);
list.add(stu4);
System.out.println("**************");
for (Student stu : list) {
System.out.println(stu.getNo() + "-" + stu.getName() + "-" + stu.getSex());
}
System.out.println("**************");
Collections.sort(list);
for (Student stu : list) {
System.out.println(stu.getNo() + "-" + stu.getName() + "-" + stu.getSex());
}
}
}

1万+

被折叠的 条评论
为什么被折叠?



