Java sorting method How to use sort

Source: Internet
Author: User

Original: http://www.cnblogs.com/minshia/p/6283858.html

Sort an array:

12345678 //对数组排序publicvoidarraySort(){    int[] arr = {1,4,6,333,8,2};    Arrays.sort(arr);//使用java.util.Arrays对象的sort方法    for(inti=0;i<arr.length;i++){        System.out.println(arr[i]);    }}

To sort the collection:

123456789101112131415161718192021222324252627282930 //对list升序排序    publicvoidlistSort1(){        List<Integer> list = newArrayList<Integer>();        list.add(1);        list.add(55);        list.add(9);        list.add(0);        list.add(2);        Collections.sort(list);//使用Collections的sort方法        for(int a :list){            System.out.println(a);        }    }    //对list降序排序    publicvoidlistSort2(){        List<Integer> list = newArrayList<Integer>();        list.add(1);        list.add(55);        list.add(9);        list.add(0);        list.add(2);        Collections.sort(list, newComparator<Integer>() {            public intcompare(Integer o1, Integer o2) {                returno2 - o1;            }        });//使用Collections的sort方法,并且重写compare方法        for(inta :list){            System.out.println(a);        }    }<br>注意:Collections的sort方法默认是升序排列,如果需要降序排列时就需要重写conpare方法

Java sorting method How to use sort

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.