package edu.wtbu;标签:list,System,add,Collections,使用,println,工具,out From: https://www.cnblogs.com/123456dh/p/17140477.html
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Demo01 {
public static void main(String[] args) {
//Collections工具类的使用
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(6);
list.add(3);
list.add(8);
list.add(2);
list.add(5);
//sort排序
System.out.println("排序前:"+list);//排序前:[1, 6, 3, 8, 2, 5]
Collections.sort(list);
System.out.println("排序后:"+list);//排序后:[1, 2, 3, 5, 6, 8]
//binarySearch
System.out.println( Collections.binarySearch(list,8));//5
System.out.println( Collections.binarySearch(list,9));//-7:没有找到
//copy复制
List<Integer> dest = new ArrayList<>();
for (int i = 0; i <list.size() ; i++) {
dest.add(0);//先添加一个空数据,使dest.size()=list.size()
}
Collections.copy(dest,list);
System.out.println(dest);
//reverse反转
Collections.reverse(list);
System.out.println("反转之后:"+list);//反转之后:[8, 6, 5, 3, 2, 1]
//shuffle打乱
Collections.shuffle(list);
System.out.println("打乱之后:"+list);//打乱之后:[1, 3, 2, 6, 5, 8]
//补充
//list转成数组
Integer[] arr = list.toArray(new Integer[0]);//当数组长度比集合长度小时,转化之后和集合长度相同;反之,则后面均为nul
System.out.println(arr.length);//6
System.out.println(Arrays.toString(arr));//[1, 3, 2, 6, 5, 8]
//数组转成集合
String[] arr1={"张三","李四","王五"};
//集合是一个受限集合,不能添加和删除
List<String> list1 = Arrays.asList(arr1);
System.out.println(list1);//[张三, 李四, 王五]
//把基本类型数组转为集合时,需要修改为包装类型
Integer[] nums={10,20,30,40};
List<Integer> list2 = Arrays.asList(nums);
System.out.println(list2);//[10, 20, 30, 40]
}
}