十、Collections工具类

 1 public class TestCollections {
 2     public static void main(String[] args) {
 3         ArrayList<String> al=new ArrayList<String>();
 4         //向集合中一次性添加N多个元素
 5         Collections.addAll(al, "hello","world","java");
 6         System.out.println(al);//[hello, world, java]
 7         
 8         //排序
 9         Collections.sort(al);//为什么按照英文字母的升序排序?因为String类具备了比较大小的能力
10         System.out.println(al);         //[hello, java, world]
11         
12         //二分搜索
13         System.out.println(Collections.binarySearch(al, "java"));//1
14         System.out.println(Collections.binarySearch(al, "html"));//-2 -2= -(插入点+1) 推理出来插入点 1
15         
16         //集合拷贝
17         ArrayList<String> al2=new ArrayList<String>();
18         Collections.addAll(al2, "sql","sql","sql","sql4");
19         //集合拷贝注意的地方:如果源集合.size()>目标集合的.size()   IndexOutOfBoundsException
20         Collections.copy(al2, al); //将al中所有元素拷贝到al2中,[hello, java, world, sql4]
21         System.out.println(al2);
22         
23         //填 充
24         Collections.fill(al2, "html");//[html, html, html, html]
25         System.out.println(al2);
26         
27         //最大与最小
28         System.out.println("最大:"+Collections.max(al));//最大:world
29         System.out.println("最小:"+Collections.min(al));//最小:hello
30         
31         //逆序
32         Collections.reverse(al);
33         System.out.println(al);//[world, java, hello]
34         
35         //线程同步
36         List<String> list=Collections.synchronizedList(al);
37     }
38 }
原文地址:https://www.cnblogs.com/qiaoxin11/p/12831718.html