天天看点

Collections简单用法Collections简单用法

Collections简单用法

定义

而Collections则是集合类的一个工具类/帮助类,其中提供了一系列静态方法,用于对集合中元素进行排序、搜索以及线程安全等各种操作。

简要

根据定义可以知道Conllections是帮助集合类的一种工具,所以首先要了解集合类,使用过c++中stl(标准类库)的知道,stl简化了对set、map、queue等等操作,有没有一个工具将他们统一化使用,进而引出要说明的Collections的作用,用于简化和统一的操作各种集合类。

1、排序函数

  • 倒序 reverse
  • 排序 sort
  • 乱序 shuffle
  • 从后提取几个到前边 rotate

如下代码

import java.util.*;

public class T01 {
    public static void main(String[] args)
    {
        ArrayList num = new ArrayList();
        num.add();
        num.add();
        num.add();
        System.out.println(num);
        Collections.reverse(num);
        System.out.println(num);
        Collections.sort(num);
        System.out.println(num);
        Collections.shuffle(num);
        System.out.println(num);
        Collections.rotate(num, );
        System.out.println(num);

    }
}
           

运行结果

[, , ]
[, , ]
[, , ]
[, , ]
[, , ]
           

2、其他函数

  • 批量添加 addAll
  • 复制 copy
  • 全部替换 fill
  • 最值 max,min
  • 二分查找 binarySearch
  • 出现次数查询 frequency
  • 替换 replaceAll
import java.util.*;

public class T01 {
    public static void main(String[] args)
    {
        ArrayList num = new ArrayList();
        num.add();
        num.add();
        num.add();
        Collections.addAll(num, ,,, );
        System.out.println("num addAll:"+num);
        ArrayList num2 = new ArrayList();
        Collections.addAll(num2, , );
        System.out.println("num2:"+num2);
        Collections.copy(num, num2);
        System.out.println("cype:"+num);
        Collections.fill(num2, );
        System.out.println("fill:"+num2);
        System.out.println("max:"+Collections.max(num)+"\n"+"min:"+Collections.min(num));
        Collections.sort(num);
        System.out.println("二分查找位置:"+Collections.binarySearch(num, ));
        System.out.println("次数查询:"+Collections.frequency(num, ));
        Collections.replaceAll(num, , );
        System.out.println("替换:"+num);
    }
}
           

运行结果:

num addAll:[, , , , , , ]
num2:[, ]
cype:[, , , , , , ]
fill:[, ]
max:
min:
二分查找位置:
次数查询:
替换:[, , , , , , ]