Java Study Notes 33 (Collection framework 7: Collections tool class ),

Source: Internet
Author: User

Java Study Notes 33 (Collection framework 7: Collections tool class ),

The array has a tool class and operations on the array.

The collection also has a tool class: Collections

Examples of common methods:

Package demo; import java. util. arrayList; import java. util. collections; import java. util. list; public class CollectionDemo {public static void main (String [] args) {function1 (); function2 (); function3 ();} public static void function1 () {// sort sorting: it must be a List set, sorted in ascending order // String, in alphabetical order List <String> list = new ArrayList <String> (); list. add ("a"); list. add ("d"); list. add ("s"); list. add ("g"); Collections. sort (list); System. out. println (list); // [a, d, g, s]} public static void function2 () {// binary search, note that the list set must be a List set. // the prerequisite for semi-query is to complete the sorting list <Integer> list = new ArrayList <Integer> (); list. add (11); list. add (3); list. add (16); list. add (9); list. add (15); Collections. sort (list); System. out. println (list); // [3, 9, 11, 15, 16] int index = Collections. binarySearch (list, 11); System. out. println (index); // 2 // The element with index 2 is 11} public static void function3 () {// List <Integer> list = new ArrayList <Integer> (); for (Integer I = 1; I <10; I ++) {list. add (I);} System. out. println (list); // [1, 2, 3, 4, 5, 6, 7, 8, 9] Collections. reverse (list); // flip collection System. out. println (list); // [9, 8, 7, 6, 5, 4, 3, 2, 1] Collections. shuffle (list); // randomly arrange System. out. println (list); // [7, 3, 4, 5, 8, 2, 6, 9, 1] // The output is different each time }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.