A brief talk on object array or list sort and collections sort principle _java

Source: Internet
Author: User
Tags comparable sorted by name static class

It is often necessary to sort the list, small to list<string>, and to sort the custom classes. You do not need to merge or heap sort yourself. Simple implementation of an interface can be.

This article will first introduce the use of collections to order list<string> , and then talk about the principle of Collections.sort,

And then how to sort the custom classes,

Finally, we 'll introduce another way to sort custom objects using collections sort, and make a simple performance comparison between the two sorts.

1. The principle of list<string> sorting and Collections.sort

The code is as follows

list<string> stringlist = new arraylist<string> (); 
Stringlist.add ("nice"); 
Stringlist.add ("Delicious"); 
Stringlist.add ("Able"); 
Stringlist.add ("Moon"); 
Stringlist.add ("Try"); 
Stringlist.add ("friend"); 
 
Collections.sort (stringlist); 
 
for (String str:stringlist) { 
  System.out.println (str); 

Among them collections is java.util.Collections.

View the sort implementation in collections

@SuppressWarnings ("unchecked") public 
static <t extends comparable< Super t>> void Sort (list<t> List) { 
  object[] array = List.toarray (); 
  Arrays.sort (array); 
  int i = 0; 
  Listiterator<t> it = List.listiterator (); 
  while (It.hasnext ()) { 
    it.next (); 
    It.set ((T) array[i++]); 
  } 
 

From this, we can see that the ordering body is arrays.sort (array); The Arrays sort implementation is

public static void sort (object[] array) { 
  //BEGIN android-changed 
  comparabletimsort.sort (array); 
  End Android-changed 
} 

Keep tracking,Comparabletimsort 's sort implementation Comparabletimsort.sort

static void sort (object[] a) to static void sort (object[] A, int lo, int hi) to private static void Binarysort (object[) A, int l o, int hi, int start). In Binarysort, the size comparison section is divided into

comparable<object> pivot = (comparable) A[start]; 
int left = lo; 
int right = start; 
Assert left <= right; 
 
While [left < right] { 
  int mid = (left + right) >>> 1; 
  if (Pivot.compareto (A[mid]) < 0) Right 
    = mid; 
  else left 
    = mid + 1; 

The CompareTo of object is invoked to compare. The CompareTo method is already overridden by default similar to string and integer types . So you can compare them yourself .

2, the custom class to compare

Through the above introduction to understand the principle of collections sorting, the following describes the ordering of custom objects, first look at the next integer and string comparison principle, and then describe how to compare the custom class

2.1 We looked at the object's implementation and found that there was no CompareTo method,

And look at the Integer definition

 
 

And look at the definition of string.

Public final class String implements Java.io.Serializable, Comparable<string>, charsequence

We can see that they all inherit from comparable.

2.2 View Comparable interface

It can be found that there is only one method in comparable

Java code

public int compareTo (T o); 

That is, the comparable CompareTo method is actually invoked in the Binarysort method, so that as long as it inherits from comparable,

and implement CompareTo, you can call Collections.sort to sort the custom objects

2.3 Comparison of custom classes

The following code for the user to sort, first sorted by name, if the same name, then by age from small to large sort

Java code

public class Maintest {public static void main (string[] args) {list<user> userlist = new Arraylist&lt ;  
    User> ();  
    Userlist.add (New User ("Lucy", 19));  
    Userlist.add (New User ("Jack", 19));  
    Userlist.add (New User ("Jim", 19));  
    Userlist.add (New User ("James", 19));  
    Userlist.add (New User ("Herry", 19));  
    Userlist.add (New User ("Luccy", 19));  
    Userlist.add (New User ("James", 18));  
 
    Userlist.add (New User ("Herry", 20));  
 
    Collections.sort (userlist);  
    for (User user:userlist) {System.out.println (User.getname () + "\t\t" + user.getage ());  
    }} private static class User implements comparable<user> {private String name;  
 
    private int age;  
      Public User (String name, int age) {this.name = name;  
    This.age = age; @Override public int CompareTo (User another) {int comparename = This.name.compareTo (Another.getnam  
      E ()); if (Comparename = = 0) {return (This.age = = Another.getage () 0: (This.age > Another.getage () 1:-1));  
    return comparename;  
    Public String GetName () {return name;  
    public int getage () {return age;  }  
  }  
}

The output after execution is:

XML code:

Herry  
herry    Jack James  
James  
luccy    -  
Lucy    19 

You can see that it takes only two points

A, inherit from comparable

Java code

private static class User implements Comparable<user>

B, implement CompareTo method

The public int CompareTo (User another) above is the principal of the comparison

You can see the int comparename = This.name.compareTo (Another.getname ()), which indicates the comparison name

If greater than return 1, equal to return 0, less than will return-1.

If equal, the size of the int age is compared.

The above is greater than the return of 1, equal to 0, less than the return-1 is also used to binarysort comparison basis.

3, using the collections sort of overloaded functions to sort the custom objects

The code below, still the same as the 2 in the first comparison of names, if equal to compare age output

Java code

public class Maintest {public static void main (string[] args) {list<user> userlist = new Arraylist&lt ;  
    User> ();  
    Userlist.add (New User ("Lucy", 19));  
    Userlist.add (New User ("Jack", 19));  
    Userlist.add (New User ("Jim", 19));  
    Userlist.add (New User ("James", 19));  
    Userlist.add (New User ("Herry", 19));  
    Userlist.add (New User ("Luccy", 19));  
    Userlist.add (New User ("James", 18));  
 
    Userlist.add (New User ("Herry", 20));  
        Collections.sort (userlist, New comparator<user> () {public int compare (user user1, user user2) {  
        int comparename = User1.getname (). CompareTo (User2.getname ());  if (Comparename = = 0) {return (user1.getage () = = User2.getage ()? 0: (User1.getage () > User2.getage ()? 1  
        :-1));  
      return comparename;  
 
    }  
    });  
    for (User user:userlist) {System.out.println (User.getname () + "\t\t" + user.getage ()); }} priVate Static class User {private String name;  
 
    private int age;  
      Public User (String name, int age) {this.name = name;  
    This.age = age;  
    Public String GetName () {return name;  
    public int getage () {return age;  }  
  }  
}

You can see

Java code

Collections.sort (userlist, New comparator<user> ()) 

As the main body of the comparison, and realized the comparator compare method. Here's how it works.

Tracking collections.

Java code

public static <T> void sort (list<t> List, comparator< super t> C)

To

Java code

public static <T> void sort (t[] A, comparator< Super t> C)

To

Java code

private static void MergeSort (object[] src, object[] dest, int low, int high, int off, Comparator c) 

You can find the code as follows:

Java code

if (length < Insertionsort_threshold) {for  
  (int i=low; i 
 

Call the comparator Compare method

4, the comparison of the two kinds of sorting performance

Binarysort need to compare NLG (n) times , the worst case n^2 Move

The mergesort is a continuous two-point, two-point to a small part of the insertion sort. So it will compare NLG (n) times and move NLG (n) Times . But it needs to replicate a copy of the source data, so it takes up one more space.

So the actual situation can be selected according to

The above article on the object array or list sorting and collections sorting principle is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

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.