Collections工具类的使用
Collections:操作Collection、Map的工具类
常用方法
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
list.add(456);
list.add(-89);
list.add(-23);
System.out.println(list); //[123, 456, 456, -89, -23]
//反转
Collections.reverse(list);
System.out.println(list); //[-23, -89, 456, 456, 123]
//随机排序
Collections.shuffle(list);
System.out.println(list); //[456, 456, 123, -23, -89]
//排序(从小到大)
Collections.sort(list);
System.out.println(list); //[-89, -23, 123, 456, 456]
//交换位置
Collections.swap(list, 0, 1);
System.out.println(list); //[-23, -89, 123, 456, 456]
//出现频率
int frequency = Collections.frequency(list, 456);
System.out.println(frequency); //2
//复制
List destList = Arrays.asList(new Object[list.size()]);
System.out.println(destList.size()); //5
Collections.copy(destList, list);
//报异常!
// List destList = new ArrayList();
// Collections.copy(destList, list);
System.out.println(destList); //[-23, -89, 123, 456, 456]
如何使集合线程安全
//Collections 类中提供了多个 synchronizedXxx() 方法,该方法可使将指定集
//合包装成线程同步的集合,从而可以解决多线程并发访问集合时的线程安全问题
ArrayList list = new ArrayList();
list.add(123);
list.add(456);
//此时,返回的 synchronizedList 即为线程安全的
List synchronizedList = Collections.synchronizedList(list);