您的位置:首页 > 新闻 > 热点要闻 > Collection

Collection

2024/12/26 20:32:37 来源:https://blog.csdn.net/qq_63126439/article/details/142203201  浏览:    关键词:Collection

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();}}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com