Collections是集合框架的工具类,里面定义的都是静态方法。
Collections和Collection的区别:
1. java.util.Collection 是集合框架中的一个顶层接口,它提供了对集合对象进行基本操作的通用接口方法。Collection接口在Java 类库中有很多具体的实现,Collection接口的意义是为各种具体的集合提供了最大化的统一操作方式。
2. java.util.Collections 是一个包装类。它包含有各种有关集合操作的静态多态方法。此类不能实例化,就像一个工具类,服务于Java的Collection框架。
Collections常用方法:
import java.util.*;
public class CollectionsDemo {
public static void main(String[] args) {
List<String> lt = new ArrayList<String>();
lt.add("sfafa");
lt.add("gs");
lt.add("fhtryfi");
lt.add("dgfsdg");
lt.add("ahtryi");
/*1. 排序:默认为自然顺序,可添加比较器*/
Collections.sort(lt/*,new StrLenComparator()*/); //根据比较器进行比较
/*2. 最值:根据排序结果,第一个为最小值,最后一个为最大值,也可以直接可添加比较器*/
System.out.println("min:"+Collections.min(lt/*,new StrLenComparator()*/));
System.out.println("max:"+Collections.max(lt/*,new StrLenComparator()*/));
/*3. 二分查找:找到则返回角标,找不到则返回 -(插入点)-1 ,默认为自然顺序,可添加比较器*/
System.out.println("index:"+Collections.binarySearch(lt, "gs"/*,new StrLenComparator()*/));
/*4. 对集合进行随机排序*/
Collections.shuffle(lt);
/*5. 反转集合中元素的顺序*/
Collections.reverse(lt);
/*6. 在指定列表的指定位置处交换元素*/
Collections.swap(lt, 2, 3);
/*7. 使用指定元素替换指定列表中的所有元素*/
Collections.fill(lt, "hh");
Iterator<String> it = lt.iterator();
while(it.hasNext())
{
System.out.println(it.next());
}
orderDemo();
}
public static void orderDemo()
{
/*8.强行逆转实现 Comparable 接口的对象 collection 的自然顺序,并返回一个比较器。*/
/*也可以对已存在的比较器进行强行逆转*/
//TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder());
TreeSet<String> ts = new TreeSet<String>(Collections.reverseOrder(new StrLenComparator()));
ts.add("abcde");
ts.add("aaa");
ts.add("k");
ts.add("cc");
Iterator it2 = ts.iterator();
while(it2.hasNext())
{
System.out.println(it2.next());
}
}
}
class StrLenComparator implements Comparator<String>
{
public int compare(String s1,String s2)
{
if(s1.length()>s2.length())
return 1;
if(s1.length()<s2.length())
return -1;
return s1.compareTo(s2);
}
}