当前位置:网站首页>7.Collections tool class

7.Collections tool class

2022-08-09 09:32:00 come here my bear

Collections tool class

  • Concept: Collection tool class, which defines common collection methods other than access
  • Method:
    • public static void reverse(List list) reverses the order of elements in the collection
    • public static void shuffle(List list) Randomly reset the order of collection elements (shuffle)
    • public static void sort(List list) sort in ascending order (the element type must implement the Comparable interface)
    • binarySearch Binary Search
    • copy copy
package com.jhkj.map;import java.util.ArrayList;import java.util.Arrays;import java.util.Collections;import java.util.List;/*** Use of Collections tool class*/public class Demo4 {public static void main(String[] args) {ArrayList list = new ArrayList<>();list.add(1);list.add(8);list.add(5);list.add(9);list.add(78);System.out.println("Number of elements: " + list.size());System.out.println(list.toString());// sort sort default ascending orderSystem.out.println("-----------------");System.out.println("before sorting" + list.toString());Collections.sort(list);System.out.println("After sorting" + list.toString());// binarySearch binary searchint i = Collections.binarySearch(list, 5);System.out.println(i);// copy copyArrayList dest = new ArrayList<>();for (int k = 0; k < list.size(); k++) {dest.add(0);}Collections.copy(dest,list);System.out.println(dest.toString());// reverse reverseCollections.reverse(list);System.out.println("After inversion: " + list);// shuffleCollections.shuffle(list);System.out.println("After shuffling: " + list);// Supplement: convert list to arraySystem.out.println("---------list into array------");Integer[] array = list.toArray(new Integer[0]);System.out.println(array.length);System.out.println(Arrays.toString(array));// convert array to collectionSystem.out.println("----------The array is converted into a collection-------");String[] names = {"Zhang San", "Li Si", "Wang Wu"};// The collection is a restricted collection and cannot be added or removedList asList = Arrays.asList(names);System.out.println(asList);// When converting an array of basic types into a collection, it needs to be modified to a wrapper class// int[]Integer[] nums = {100,200,300,400};// iny[]List list1 = Arrays.asList(nums);System.out.println(list1);}}
原网站

版权声明
本文为[come here my bear]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/221/202208090923102813.html