Collections集合工具类

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, 只]
    }
}

猜你喜欢

转载自www.cnblogs.com/wurengen/p/10540260.html