java.util.Collections:是集合工具类
作用:Collections不是集合,而是集合的工具类
常用API
addAll
package Collections;import java.util.ArrayList;
import java.util.Collections;public class CollectionsDemo {public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();//添加到数组里面Collections.addAll(list,"aaa","sasa","gdg","gfd","hgf","fds","reg");System.out.println(list);}
}
shuffle
package Collections;import java.util.ArrayList;
import java.util.Collections;public class CollectionsDemo {public static void main(String[] args) {ArrayList<String> list = new ArrayList<>();//添加到数组里面Collections.addAll(list,"aaa","sasa","gdg","gfd","hgf","fds","reg");System.out.println("打乱前:"+list);Collections.shuffle(list);System.out.println("打乱后:"+list);}
}
随机取名的实现
package Collections;import java.util.ArrayList;
import java.util.Collections;
import java.util.Random;public class CollectionDemo2 {public static void main(String[] args) {ArrayList<String> list1 = new ArrayList<>();Collections.addAll(list1,"撒娇了","萨马卡罗","大撒大撒","的撒旦","改好发给","发你回家","客家话");ArrayList<String> list2 = new ArrayList<>();for (int j = 1 ; j <= 10;j++) {System.out.println("------第"+j+"轮开始------");int count = list1.size();Random rd = new Random();for (int i = 0; i < count; i++) {int index = rd.nextInt(list1.size());String name = list1.remove(index);list2.add(name);System.out.println(name);}list1.addAll(list2);list2.clear();}}
}