1.collections工具类是操作Collection、Map的工具类
2.Collections 类中提供了多个 synchronizedXxx() 方法,该方法可使将指定集合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题
3.思考:Collection 和 Collections的区别?
- List list = new ArrayList();
- list.add(123);
- list.add(123);
- list.add(43);
- list.add(765);
- list.add(-97);
- list.add(0);
-
- //返回的list1即为线程安全的List
- List list1 = Collections.synchronizedList(list);
Collections.reverse(list);
Collections.shuffle(list);
Collections.swap(list,1,3);
Collections.sort(list);
- List list = new ArrayList();
- list.add(123);
- list.add(43);
- list.add(765);
- list.add(-97);
- list.add(0);
-
- Collections.sort(list, new Comparator() {
- @Override
- public int compare(Object o1, Object o2){
- if (o1 instanceof Integer && o2 instanceof Integer){
- return -Integer.compare(((Integer) o1),(Integer) o2);
- }else {
- throw new RuntimeException("输入的格式不符合要求");
- }
- }
- });
int frequency = Collections.frequency(list, 123);
- //错误写法:
- // 报异常:IndexOutOfBoundsException("Source does not fit in dest")
- // List dest = new ArrayList();
- // Collections.copy(dest,list);
-
- //正确写法:
- List dest = Arrays.asList(new Object[list.size()]);
- System.out.println(dest.size());//list.size();
- Collections.copy(dest,list);
-
- System.out.println(dest);
Collections.replaceAll(list,123,1234);
- //实例化的时候加了泛型,下边的定制排序写法不同
- List
list = new ArrayList<>(); - list.add(123);
- list.add(43);
- list.add(765);
- list.add(-97);
- list.add(0);
Integer max1 = Collections.max(list);//765
- Integer max = Collections.max(list, new Comparator
() { - @Override
- public int compare(Integer o1, Integer o2) {
- return -Integer.compare(o1, o2);
- }
- });
- System.out.println(max);//-97
Integer min1 = Collections.min(list);//-97
- Integer min = Collections.min(list, new Comparator
() { - @Override
- public int compare(Integer o1, Integer o2) {
- return -Integer.compare(o1, o2);
- }
- });
- System.out.println(min);//765