一、Collections算法类
- Java集合框架将针对不同数据结构算法的实现都保存在工具类中
- Collections类定义了一系列用于操作集合的静态方法
Collections类常用方法
- Collections和Collection不同,前者是集合的操作类,后者是集合接口
- Collections提供的常用静态方法
1.sort()排序
2.binarySearch();查找
3.max()\min();查找最大\最小值
【注:详见帮助文档】
具体实现
package cn.lch.collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsDemo1 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("hdf");
list.add("jfgjh");
list.add("fdsh");
list.add("okdf ");
list.add("add");
list.add("fke");
list.add("buke");
list.add("apple");
String strMax = (String)Collections.max(list);
String strMin = (String)Collections.min(list);
System.out.println(strMax+" - "+strMin);
Collections.sort(list);
for(String str:list){
System.out.println(str);
}
System.out.println(Collections.binarySearch(list, "apple"));
System.out.println("*****************");
Collections.reverse(list);
for(String str:list){
System.out.println(str);
}
}
}
输出结果:
okdf - add
add
apple
buke
fdsh
fke
hdf
jfgjh
okdf
1
*****************
okdf
jfgjh
hdf
fke
fdsh
buke
apple
add
Collections排序
- Collections类可以对集合进行排序、查找和替换操作
- 实现一个类的对象之间比较大小
1.该类要实现Comparable接口
2.重写compareTo()方法
package cn.lch.collections;
public class Student implements Comparable {
private int number;
private String name;
private String sex;
public Student(){}
public Student(int number,String name,String sex){
this.number = number;
this.name = name;
this.sex = sex;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public int compareTo(Object o) {
Student student = (Student)o;
if(this.number == student.number){
return 0;
}else if(this.number>student.number){
return 1;
}else{
return -1;
}
}
}
package cn.lch.collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
public class CollectionsDemo2 {
public static void main(String[] args) {
List<Student> list = new ArrayList<Student>();
Student s1 = new Student(1,"赵如花","女");
Student s2 = new Student(7,"马冬梅","女");
Student s3 = new Student(6,"王大锤","男");
Student s4 = new Student(8,"张三","男");
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
Collections.sort(list);
for(Student stu:list){
System.out.println(stu.getNumber()+" - "+stu.getName()+" - "+stu.getSex());
}
}
}
输出结果:
1 - 赵如花 - 女
6 - 王大锤 - 男
7 - 马冬梅 - 女
8 - 张三 - 男