package com.qiaoyx.java;
import org.junit.Test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
*
* Collections:操作Collection和Map的工具类
*
* 面试题:Collections和Collection的区别
* @author: qyx
* @date: 2022-08-09 20:54
* @desc:
*/
public class CollectionsTest {
@Test
public void test1(){
List list = new ArrayList();
list.add(123);
list.add(43);
list.add(765);
list.add(-97);
list.add(0);
System.out.println(list);
//对list进行反转
Collections.reverse(list);
System.out.println(list);
//对list进行随机排序
Collections.shuffle(list);
System.out.println(list);
//对list进行自然排序
Collections.sort(list);
System.out.println(list);
//交换索引位置上的元素
Collections.swap(list,2,4);
System.out.println(list);
//返回集合中指定元素的出现次数
int frequency = Collections.frequency(list, 123);
System.out.println(frequency);
}
@Test
public void test2(){
List list = new ArrayList();
list.add(123);
list.add(43);
list.add(765);
list.add(-97);
list.add(0);
List dest = Arrays.asList(new Object[list.size()]);
System.out.println(dest);
Collections.copy(dest,list);
System.out.println(dest);
/*
Collections提供了多个synchronizedXxx()方法,
包装成线程安全的集合并返回,解决并发时的线程安全问题
*/
List list1 = Collections.synchronizedList(list);
}
}
08-31
1万+
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
11-01
206
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
09-26
455
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)