- Collections工具类:
概念:集合工具类,定义了除了存取以外的集合常用方法。
此类完全由在collection上进行操作或返回collection的静态方法组成。它包含在cooletion上操作的多态算法,即“包装类”,包装类返回由指定collection支持的新collection.以及少数的其他内容。
如果为此类的方法所提供的collection或类对象为null,则这些方法都将抛出NullPotionterException
I. public static void sort<List list> // 升序排序(元素类型必须实现Comparable接口)
//传入的集合List (T可以是Strings Integers)是要继承 Comparable,且Comparabl的要求是 给的可以是T 也可以是T的父类 但必须是可以排序的
/// public static <T extends Comparable<? super T>> void sort(List list){
Object[] a =list.toArray();
Arrays.sort(a);
ListIterator i = list.listTterator();//迭代器
for(int j=0;j<a.length;j++){
i.next();
i.set((T)a[j]);}}
public static void sort(Object o){
if(LegacyMergeSort.userRequested)
LegacyMergeSort(a);
else
ComparableTimSort.sort(a);}
public static void legacyMergeSort(Object[] a){
Object[] aux = a.clone();
mergeSort(aux,a,0,a.length,0);}………………………
//排序,要求:必须实现Comparable,必须可与自身类型比,以及父类类型比
II. public static void reverse(List<?> list) //反转、倒置元素
此方法以线性时间运行。
III. public static void shuffle(List<?> list) //随机重置顺序
main(){
List list = new ArrayList();
list.add(1);
list.add(4);
list.add(5);
list.add(7);
Collections.reverse(list);//倒序
Collections.shuffle(list);//随机
Collections.short
for(int i = 0; i < list.size(); i++){
System.out.println(list.get(i)); } }
源码: public int comparator(Integer anotherInteger){
return compare(this.value, anotherInteger.value);}
//返回-1 this靠前 返回1 this靠后 返回 0 二者相同
public static int compare(int x,int y){
return (x < y) ? -1 : ((x==y) ? 0 :1);}
String实现字典排序 Integer 实现大小排序
main(){
List stus =new ArrayList();
stus.add(new Student(12));
stus.add(new Student(14));
stus.add(new Student(13));
Collections.sort(stus); }
class Student implements Comparable{
@Override
public int compareTo(Student o ){
if(this.age > o.age){
return 100;
}else if(this.age < o.age){
return -100
}
return 0;} }
经验:一级目标能看懂、能调用,二级目标能定义、能设计