JAVA中的Collections集合工具类

JAVA中的Collections集合工具类

  • java.util.Collection 是集合接口
    java.util.Collections 是集合工具类,方便集合的操作
  • Collections.synchronizedList() :将集合转为线程安全的
  • Collections.sort() : 对参数列表中的List集合进行排序,Set集合需转成List集合再进行排序
    排序的List集合中的自定义类需要实现 java.lang.Comparable 接口
public class CollectionsTest01 {
    public static void main(String[] args) {
        //ArrayList不是线程安全的
        List<String> list = new ArrayList<>();
        //添加元素
        list.add("abz");
        list.add("abe");
        list.add("aba");
        //将ArrayList转变为线程安全的,返回数组
        System.out.println(Collections.synchronizedList(list)); //[abz, abe, aba]
        //排序
        Collections.sort(list);
        //遍历
        for (String str : list){
            System.out.println(str);
            //aba
			//abe
			//abz
        }

        System.out.println("=======================================");

        //创建一个Set集合
        Set<AnotherWuGui> anotherWuGui = new HashSet<>();
        //添加乌龟对象
        anotherWuGui.add(new AnotherWuGui(1000));
        anotherWuGui.add(new AnotherWuGui(3));
        anotherWuGui.add(new AnotherWuGui(99));
        //对Set集合排序:
        //需要先将Set集合转为List集合
        List<AnotherWuGui> l = new ArrayList<>(anotherWuGui);
        //再进行排序,(AnotherWuGui类需要实现java.lang.Comparable接口)
        Collections.sort(l);
        //遍历
        for (AnotherWuGui wugui : l){
            System.out.println(wugui);
            //小乌龟的年龄:3
			//小乌龟的年龄:99
			//小乌龟的年龄:1000
        }
    }
}
class AnotherWuGui implements Comparable<AnotherWuGui>{
    int age;

    public AnotherWuGui(int age) {
        this.age = age;
    }
    public String toString(){
        return ("小乌龟的年龄:" + this.age);
    }

    @Override
    public int compareTo(AnotherWuGui o) {
        return this.age - o.age;
    }
}
//运行结果:
[abz, abe, aba]
aba
abe
abz
=======================================
小乌龟的年龄:3
小乌龟的年龄:99
小乌龟的年龄:1000
  • 如果直接对Set集合进行排序,编译器会报错:
    在这里插入图片描述
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值