A summary of how collections and arrays are sorted in Java _java

Source: Internet
Author: User
Tags array length comparable

By convention, you should use the existing class library as much as possible while using Java programming, and of course you can write a sorting method or framework yourself, but how many people can write better than the JDK? Another benefit of using existing classes is that the code is easy to read and maintain, and this article is about how to sort by using an existing class library array and various collection containers (some examples from the article are Java Developers Almanac 1.4)

The first thing to know is two classes: Java.util.Arrays and java.util.Collections (Note and collection) collection are the top-level interfaces of the collection framework, and the collections contains many static methods. We use the arrays array to sort, and use collections to sort the binding frame container, such as arrayslist,linkedlist.

Examples include the import java.util.* and other shell codes, such as classes and static main methods, and I'll write out all the code in the first example, followed by no exceptions.

To sort a set of arrays

For example, there is an array of integers:

Copy Code code as follows:

int[] Intarray = new int[] {4, 1, 3,-23};

How do we sort? Are you thinking of a quick sort algorithm at this time? Look at the following implementation methods:
Copy Code code as follows:

Import java.util.*;
public class sort{
public static void Main (string[] args) {
int[] Intarray = new int[] {4, 1, 3,-23};
Arrays.sort (Intarray);

So we sorted the intarray in ascending order using the arrays static method sort (), and now the array has become { -23,1,3,4}.

If it is a character array:

Copy Code code as follows:

string[] Strarray = new string[] {"Z", "a", "C"};

We use:
Copy Code code as follows:

Arrays.sort (Strarray);

The result of sorting is that {C,a,z},sort () is sorted in ascending order according to the natural sequence of the elements. If you want to be insensitive to case, you can write this:
Copy Code code as follows:

Arrays.sort (Strarray, String.case_insensitive_order);

Of course, we can also specify a section of the array to sort for example, we want to sort the parts of table 0-2 (assuming that the array length is greater than 3), and the rest of the list, we can use:
Copy Code code as follows:

Arrays.sort (strarray,0,2);

In this way, we just sort the first three elements without affecting the rest.

Of course, someone would think, how do I sort in descending order? Among the many sort methods is a

Copy Code code as follows:

Sort (t[] A, comparator< Super t> C)

We use comparator to get a reverse-order comparator, comparator will explain later, taking the preceding intarray[] as an example:
Copy Code code as follows:

Arrays.sort (Intarray,comparator.reverseorder ());

In this way, we get the result is {4,3,1,-23}. If you do not want to modify the original code we can also use:
Copy Code code as follows:

Collections.reverse (Arrays.aslist (Intarray));

Gets the inverse order of the array. The result is also 4,3,1,-23}.

Now that the situation has changed, our array is no longer a base data type (primtive type) or an array of string types, but an array of objects. The natural order of this array is unknown, so we need to implement the comparable interface for that class, for example, we have a name class:

Copy Code code as follows:

Class Name implements comparable<name>{
Public String Firstname,lastname;
Public Name (String firstname,string lastName) {
public int compareTo (Name o) {//implementation interface
int Lastcmp=lastname.compareto (o.lastname);
Return (Lastcmp!=0?lastcmp:firstname.compareto (o.firstname));
Public String toString () {//easy to output test
Return firstname+ "" +lastname;

In this way, when we sort the array of objects, we compare the LastName, then compare FirstName and then draw the order of the two objects, as implemented in CompareTo (Name o). You might try it with a program:
Copy Code code as follows:

Import java.util.*;
public class Namesort {
public static void Main (string[] args) {
Name namearray[] = {
New Name ("John", "Lennon"),
New Name ("Karl", "Marx"),
New Name ("Groucho", "Marx"),
New Name ("Oscar", "Grouch")
Arrays.sort (NameArray);
for (int i=0;i<namearray.length;i++) {
System.out.println (Namearray[i].tostring ());

The result is as we wish:
Copy Code code as follows:

Oscar Grouch
John Lennon
Groucho Marx
Karl Marx

sort the collection frame

If the Arrays.sort () array is already understood, the use of the collection framework is similar. Just replace arrays with collections, note that collections is a class and collection is an interface, although it's only one "s" but they mean something completely different.

If there is such a linked list:

Copy Code code as follows:

LinkedList list=new LinkedList ();
List.add (4);
List.add (34);
List.add (22);
List.add (2);

We only need to use:
Copy Code code as follows:

Collections.sort (list);

The elements in ll can be sorted in order from small to large, and the result is:
Copy Code code as follows:

[2, 4, 22, 34]

If the elements inside the LinkedList are string, the same will be sorted from small to large as the basic data type.

If you want to implement a sort of reverse order, which is from achieving a small sort:

Copy Code code as follows:

Collections.sort (List,collectons.reverseorder ());

If the elements inside the LinkedList are custom objects, you can implement the comparable interface just like the name object above, so that Collection.sort () is sorted for you.

If you want to sort an object according to your own ideas, you can use the

Copy Code code as follows:

Sort (list<t> List, comparator< super t> C)

This method is sorted, before giving an example, first explain the use of comparator, the format of the comparable interface:
Copy Code code as follows:

Public interface Comparator<t> {
int compare (t O1, T O2);

In fact, the comparator of the int compare (T o1,t O2) and the comparable in CompareTo () method of writing similar. In the above name class our comparison starts from the LastName, this is the western custom, in China, we want to compare from the Fristname, do not want to revise the original code, this time, comparator can come in use:
Copy Code code as follows:

Final comparator<name> first_name_order=new comparator<name> () {
public int Compare (name n1, name N2) {
int Firstcmp=n1.firstname.compareto (n2.firstname);
Return (Firstcmp!=0?firstcmp:n1.lastname.compareto

Such a custom comparator First_name_order is written.

Converts the array of names in the last example to list:

Copy Code code as follows:

List<name> list=arrays.aslist (NameArray);
Collections.sort (List,first_name_order);

This allows us to successfully use our own defined comparer to set the sort.

Related Article

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.