Collection工具类:
package com.mokuiran.collection;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
/**
* collection工具类
*/
public class Tools {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(3);
list.add(15);
list.add(22);
list.add(18);
//sort排序
System.out.println("排序之前:"+list.toString());//输出,排序之前:[10, 3, 15, 22, 18]
Collections.sort(list);
System.out.println("排序之后:"+list.toString());//输出,排序之后:[3, 10, 15, 18, 22]
//binarySearch二分查找
int i = Collections.binarySearch(list,18);
System.out.println(i);//找出排序后18的位置,输出 3
//copy复制
ArrayList<Integer> list1 = new ArrayList<>();
for (int k=0;k<list.size();k++){
list1.add(0);
}//新数组需要长度
Collections.copy(list1,list);
System.out.println(list1.toString());//输出[3, 10, 15, 18, 22]
//reverse反转
Collections.reverse(list);
System.out.println("反转:"+list.toString());
//shuffle打乱
Collections.shuffle(list);
System.out.println("打乱之后:"+list);//每次输出都不一样
//补充
//集合转换成数组
Integer[] arr = list.toArray(new Integer[10]);//数组必须比所转换的数组大
System.out.println(arr.length);//输出10
System.out.println(Arrays.toString(arr));//输出[18, 15, 10, 22, 3, null, null, null, null, null]
//数组转集合
String[] names = {"张三","李四","王五"};
//集合是一个受限的集合,不能添加和删除
List<String> list2 = Arrays.asList(names);
System.out.println(list2);
//基本类型数组转换成集合时,需要修改为包装类型
Integer[] nums = {100,200,300,400,500};
List<Integer> list3 = Arrays.asList(nums);
System.out.println(list3);
}
}
标签:10,18,list,System,Collection,println,-----,集合,out From: https://www.cnblogs.com/mokuiran/p/16600930.html