collection常用方法(小工具)
阿新 • • 發佈:2022-03-08
package Collection; import java.util.*; /** * collection 小工具 * * @author liu */ public class Demo01 { public static void main(String[] args) { List<Integer> arrayList = new ArrayList<>(); arrayList.add(1); arrayList.add(12); arrayList.add(21); arrayList.add(15); arrayList.add(15); arrayList.add(16); //sort排序 System.out.println("排序前:" + arrayList); Collections.sort(arrayList); System.out.println("排序後:" + arrayList); //binarySearch查詢 System.out.println("--------查詢-----------"); int i = Collections.binarySearch(arrayList, 15); System.out.println(i); //copy複製,需要新增元素 System.out.println("--------複製-----------"); List<Integer> listt = new ArrayList<>(); for (int k = 0; k < arrayList.size(); k++) { listt.add(0); } Collections.copy(listt, arrayList); System.out.println(listt); //reverse反轉 System.out.println("--------反轉-----------"); Collections.reverse(listt); System.out.println(listt); //shuffle打亂 System.out.println("--------打亂-----------"); Collections.shuffle(listt); System.out.println(listt); //補充list轉陣列 System.out.println("--------集合轉陣列-----------"); Integer[] A = listt.toArray( new Integer[10]); System.out.println(Arrays.toString(A)); //陣列轉集合 System.out.println("--------陣列轉集合-----------"); String[] name ={"張三","李思","王五"}; //轉集合後,是一個受限集合,不能新增、刪除 List<String> strList = Arrays.asList(name); //strList.add("2"); //strList.remove(0); System.out.println(strList); //陣列轉集合,型別不能為int,需要修改為包裝型別 Integer[] nums = {1,2,5,7,1,1,22}; List<Integer> list1 =Arrays.asList(nums); System.out.println(list1); } }