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(1);
num.add(6);
num.add(3);
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, 2);
System.out.println(num);

}
}

运行结果

[1, 6, 3]
[3, 6, 1]
[1, 3, 6]
[3, 6, 1]
[6, 1, 3]

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(1);
num.add(6);
num.add(3);
Collections.addAll(num, 4,5,15, 4);
System.out.println("num addAll:"+num);
ArrayList num2 = new ArrayList();
Collections.addAll(num2, 10, 23);
System.out.println("num2:"+num2);
Collections.copy(num, num2);
System.out.println("cype:"+num);
Collections.fill(num2, 111);
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, 5));
System.out.println("次数查询:"+Collections.frequency(num, 4));
Collections.replaceAll(num, 4, 999);
System.out.println("替换:"+num);
}
}

运行结果:

num addAll:[1, 6, 3, 4, 5, 15, 4]
num2:[10, 23]
cype:[10, 23, 3, 4, 5, 15, 4]
fill:[111, 111]
max:23
min:3
二分查找位置:3
次数查询:2
替换:[3, 999, 999, 5, 10, 15, 23]