Java : Collections 工具类

Collection 是集合的接口, 而Collections 是一个集合的操作工具类.在这个类中里面提供有集合的基础操作: 如 反转, 排序等.

范例: 创建空集合(可以作为标记)

package com.beyond.nothing;

import java.util.Collections;
import java.util.List;

public class test {
    
    

    public static void main(String[] args) throws Exception {
    
    
        List<String> all = Collections.EMPTY_LIST;
        all.add("A");  // java.lang.UnsupportedOperationException
    }
}

范例: 利用Collections 进行集合操作

package com.beyond.nothing;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class test {
    
    

    public static void main(String[] args) throws Exception {
    
    
        List<String> all = new ArrayList<>();
        Collections.addAll(all, "A","B","C");  // 相当于调用三次 add()
        System.out.println(all);
        Collections.reverse(all);  // 进行反转
        ArrayList<String> list = new ArrayList<>();
        list.add("");
        list.add("");
        list.add("");

        Collections.copy(list, all);  // 进行拷贝
        System.out.println(all);
        System.out.println(list);

    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Beyond_Nothing/article/details/113356334