Collections 工具类

JDK 中提供了一个工具类专门用来操作集合,即 Collections,它位于 java.util 包中。Collections 类中提供了大量的方法用于对集合中的元素进行排序、查找和修改等操作。


排序操作

方法声明功能描述
static boolean addAll(Collection c, T… elements)将所有指定元素添加到指定的 collection 中
static void reverse(List list)反转指定 List 集合中元素的顺序
static void shuffle(List list)对 List 集合中的元素进行随机排序(模拟玩扑克中的”洗牌”)
static void sort(List list)根据元素的自然顺序对 List 集合中的元素进行排序
static void swap(List list, int i, int j)将指定 List 集合中 i 处元素和 j 处元素进行交换

示例代码:

import java.util.*;

public class Example {
    public static void main(String[] args){
        ArrayList list = new ArrayList();
        Collections.addAll(list, "C", "Z", "B", "K");
        System.out.println("排序前:" + list);
        Collections.reverse(list);
        System.out.println("反转后:" + list);
        Collections.sort(list);
        System.out.println("按自然顺序排序后:" + list);
        Collections.shuffle(list);
        System.out.println("洗牌后:" + list);
    }
}

查找、替换操作

方法声明功能描述
static int binarySearch(List list, Object key)使用二分法搜索指定对象在 List 集合中的索引,查找的 List 集合中的元素必须是有序的
static Object max(Collection col)根据元素的自然顺序,返回给定集合中最大的元素
static Object min(Collection col)根据元素的自然顺序,返回给定集合中最小的元素
static boolean replaceAll(List list, Object oldVal, Object newVal)用一个新的 newVal 替换 List 集合中所有的旧值 oldVal

Example.java 示例代码:

import java.util.*;

public class Example {
    public static void main(String[] args){
        ArrayList list = new ArrayList();
        Collections.addAll(list, -3, 2, 9, 5, 8);
        System.out.println("集合中的元素:" + list);
        System.out.println("集合中的最大元素:" + Collections.max(list));
        System.out.println("集合中的最小元素:" + Collections.min(list));
        Collections.replaceAll(list, 8, 0);  //将集合中的 8 用 0 替换掉
        System.out.println("替换后的集合:" + list);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值