1. 程式人生 > >Collections集合工具類

Collections集合工具類

println private hashset shuf bsp [] 自定義類 ole 工具

Collections集合工具類,專門用來對集合進行操作的。

常用方法:

  • public static<T> boolean addAll(Collection<T> c,T....elements):往集合中添加一些元素
  • public static void shuffle(List<?> list):打亂list集合順序
  • public static <T> void sort(List<?> list):將集合中的元素,按照默認規則排序,自定義類型的元素要排序,必須實現comparable,重寫接口中的方法compareTo定義排序規則。

import java.util.*;


public class CollectionsDemo {
    public static void main(String[] args) {
        demo1();
        demo2();
    }

    private static void demo2() {
        ArrayList<String> coll = new ArrayList<String>();
        Collections.addAll(coll, "只1", "sd2", "ad3", "s4");
        
//打亂 list集合中元素的位置 Collections.shuffle(coll); System.out.println(coll); } private static void demo1() { HashSet<String> h = new HashSet<>(); // 往集合中添加一些元素 Collections.addAll(h, "只", "sd", "ad", "s"); System.out.println(h);//[sd, ad, s, 只]
} }

Collections集合工具類