IT干货网

集合之Collections工具

luoye 2022年03月12日 编程设计 176 0

集合之Collections工具

以下代码使用Collections工具对集合进行操作:

package com.javalearn.collection.tool; 
 
import java.util.*; 
 
public class TestFOrTool { 
    public static void main(String[] args) { 
        List<String> list = new ArrayList<>();  // ArrayList不是线程安全的 
        Collections.synchronizedList(list);  // 变成线程安全的 
 
        list.add("cxf"); 
        list.add("asmf"); 
        Collections.sort(list);  // 排序,只能输入List 
        for (String s:list) { 
            System.out.println(s); 
        } 
 
        Set<String> set = new HashSet<>();  // Collections对集合元素排序,先把集合变成List 
        set.add("cxf"); 
        List<String> list1 = new ArrayList<>(set); 
        Collections.sort(list1); 
    } 
} 
 

输出结果:

asmf 
cxf 

评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!