Java Collection framework (Collection) and array sorting

Source: Internet
Author: User
Tags comparable

According to the Conventions, you should try to use the existing class libraries when using Java programming. Of course, you can also compile a sort method or framework by yourself, but how many people can write better than those in JDK? Another advantage of using existing classes is that the Code is easy to read and maintain. This article mainly describes how to sort arrays and collection containers using existing class libraries, (some examples in this article are from Java developers almanac 1.4.)
First, you must know two classes: Java. util. arrays and Java. util. collections (note the difference with collection) collection is the top-level interface of the Collection framework, while collections contains many static methods. We use arrays to sort arrays and collections to sort containers in combination with frameworks, such as arrayslist and sort list.
In this example, we need to add import java. util. * and other shell code, such as the class and static main method. I will write all the code in the first example, which will be omitted without exception.
 
Sort Arrays
 
For example, there is an integer array:
Int [] intarray = new int [] {4, 1, 3,-23 };
How do we sort data? Are you thinking about a fast sorting algorithm at this time? Let's take a look at the following implementation methods:

Import java. util .*;
Public class sort ...{
Public static void main (string [] ARGs )...{
Int [] intarray = new int []... {4, 1, 3,-23 };
Arrays. Sort (intarray );
}
}

In this way, we use the static method sort () of arrays to sort intarray in ascending order. Now the array has become {-23,1, 3,4 }.
 
If it is a character array:
String [] strarray = new string [] {"Z", "A", "C "};
We use:
Arrays. Sort (strarray );
After sorting, {C, A, z}, and sort () are sorted in ascending order based on the natural order of the elements. If you want to be case insensitive, write as follows:
Arrays. Sort (strarray, String. case_insensitive_order );
Of course, we can also specify a part of the array for sorting. For example, we want to sort the part 0-2 of the array table (assuming the array length is greater than 3), and the other part remains unchanged. We can use:
Arrays. Sort (strarray, 0, 2 );
In this way, we only sort the first three elements without affecting the subsequent parts.
 
Of course, some people may think, how do I sort in descending order? One of the many sort Methods
Sort (T [] A, comparator <? Super T> C)
We can use comparator to obtain a reverse comparator. comparator will explain it later. The previous intarray [] is used as an example:
Arrays. Sort (intarray, comparator. reverseorder ());
In this way, the result is {4, 3, 1,-23 }. If you do not want to modify the original code, you can also use:
Collections. Reverse (arrays. aslist (intarray ));
Returns the reverse order of the array. The result is 4, 3, 1,-23 }.

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

Class Name implements comparable <Name> ...{
Public String firstname, lastname;
Public name (string firstname, string lastname )...{
This. firstname = firstname;
This. lastname = 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 output test
Return firstname + "" + lastname;
}
}

In this way, when we sort this object array, we will first compare the lastname, then compare the firstname, and then get the order of the two objects, just like compareto (name o). Try it with a program:

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 results are as expected:

Oscar grouch
John Lennon
Groucho Marx
Karl Marx

Sort the collection framework
 
If arrays. Sort () is understood to sort arrays, the use of the Collection framework is similar. Only replace arrays with collections. Note that collections is a class and collection is an interface. Although there is only one "s" difference, their meanings are completely different.
Suppose there is such a linked list:

Jsonlist list = new jsonlist ();
List. Add (4 );
List. Add (34 );
List. Add (22 );
List. Add (2 );

We only need to use:
Collections. Sort (list );
You can sort the elements in ll in the ascending order, and the result is:
[2, 4, 22, 34]
If the element in the SORT list is string, the basic data type is also sorted from small to large.
If you want to implement reverse sorting, that is, small sorting:
Collections. Sort (list, collectons. reverseorder ());
If the elements in the sorted list are custom objects, You can implement the comparable interface like the name object above, so that collection. Sort () can be sorted for you.
 
If you want to sort an object according to your own ideas, you can use
Sort (list <t> list, comparator <? Super T> C)
This method is sorted. Before giving an example, we need to describe the use of comparator,
Format of the comparable interface:

Public interface comparator <t> ...{
Int compare (T O1, t O2 );
}

In fact, the write method of int compare (T O1, t O2) in comparator is similar to that of compareto () in comparable. In the above name class, our comparison started with lastname. This is a habit of Westerners. In China, we want to compare it from fristname and do not want to modify the original code. At this time, comparator can be used:

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
(N2.firstname ));
}
};

So that we can write a custom comparator first_name_order.
Convert the name array in the previous example to list:
List <Name> List = arrays. aslist (namearray );
Collections. Sort (list, first_name_order );
In this way, we can use our own comparator to set the sorting.

Source: http://www.xrss.cn/Info/15106.html

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.