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(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]
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值