Different sorting methods of Java ArrayList _java

Source: Internet
Author: User
Tags anonymous assert comparable sorts

Because of its functionality and flexibility, ArrayList is one of the most common collection classes used in the Java collection framework. ArrayList is a List implementation that uses a dynamic array to store elements, so that ArrayList can dynamically expand and shrink when adding and removing elements. You may have used ArrayList, so I'll skip over the basics. If you are unfamiliar with ArrayList, you can refer to its API documentation and it is easy to understand how to perform basic operations on ArrayList.
In this article, I'll discuss one of the most important operations in ArrayList, and you'll probably need to implement it in enterprise application development. It is the sort of ArrayList element.

ArrayList of Sort String objects

Consider a ArrayList store name that exists as a string (country name), and in order to sort the ArrayList, you need to call the Collections.sort () method to pass the ArrayList object made up of the country name. This method sorts the elements (the country name) in a natural order (in ascending alphabetically). Let's write a piece of code for that.
Sortarraylistascendingdescending.java

 package guru.springframework.blog.sortarraylist.ascendingdescending;
 Import java.util.ArrayList;
 Import java.util.Collections;
 public class Sortarraylistascendingdescending {private ArrayList ArrayList;
 Public sortarraylistascendingdescending (ArrayList ArrayList) {this.arraylist = ArrayList;
 Public ArrayList getarraylist () {return this.arraylist;
 Public ArrayList sortascending () {collections.sort (this.arraylist);
 return this.arraylist;
 Public ArrayList sortdescending () {Collections.sort (this.arraylist, Collections.reverseorder ());
 return this.arraylist; }
 }

In the above class, we initialize a ArrayList object in the constructor. In the SortAscending () method, we call the Collections.sort () method and pass the initialized ArrayList object as a parameter, returning the sorted ArrayList. In the SortDescending () method, we call the overloaded Collections.sort () method to sort the elements in descending order, and this version of Collections.sort () receives the ArrayList object as the first argument, one by The Collections.reverseorder () method returns the Comparator object as the second argument. We will explain the Comparator later. To test the sorting function, we will write a test code.
Sortarraylistascendingdescendingtest.java

Package guru.springframework.blog.sortarraylist.ascendingdescending;
 Import Org.junit.Test;
 Import java.util.ArrayList;
 Import static org.junit.assert.*; public class Sortarraylistascendingdescendingtest {<a href= "Http://www.jobbole.com/members/madao" > @Test </
 a> public void Testsortascendingdescending () throws Exception {ArrayList countrylist = new arraylist<> ();
 Countrylist.add ("France");
 Countrylist.add ("USA");
 Countrylist.add ("India");
 Countrylist.add ("Spain");
 Countrylist.add ("England");
 sortarraylistascendingdescending sortarraylist = new sortarraylistascendingdescending (countryList);
 ArrayList unsortedarraylist = Sortarraylist.getarraylist ();
 System.out.println ("unsorted ArrayList:" + unsortedarraylist);
 ArrayList sortedarraylistascending = sortarraylist.sortascending ();
 System.out.println ("Sorted ArrayList in ascending order:" + sortedarraylistascending);
 ArrayList sortedarraylistdescending = sortarraylist.sortdescending (); System.out.prIntln ("Sorted ArrayList in descending order:" + sortedarraylistdescending); }
 }

In the test code above, we created a ArrayList object and added 5 string objects representing the names of 5 countries. Then we call the Getarraylist (), sortascending (), and sortdescending () methods and print the ArrayList objects returned by these methods.

So far, the ArrayList elements to sort are very simple, we just call the Collections.sort () method and pass the ArrayList object that needs to be sorted as arguments. But what's more, you'll be able to sort the ArrayList in some complicated situations.
The Collections.sort () method sorts the elements of the ArrayList or comparable elements of any other List, meaning that the classes of these elements need to implement the comparable interface in the Java.lang package. Just as the String class implements the comparable interface, we can sort the ArrayList by the name of the country. Some of the other standard Java classes implement the comparable interface, including the original wrapper classes, such as Integer, short, Double, Float, Boolean, BigInteger, BigDecimal, File, and Date classes that implement the Comparable interface.

Use comparable to sort ArrayList

The

Comparable is an interface with a single compareTo () method. A class object that implements the comparable interface can be compared with other objects of the same type, and the class that implements the comparable interface needs to override the CompareTo () method, which receives an object of the same type and implements the logic of comparison between this object and another object passed to the method. The CompareTo () method returns a comparison of the int type, representing the following meaning: The
positive value indicates that the current object is larger than the object passed to CompareTo () to indicate that the current object is smaller than the object passed to the CompareTo ()
Zero indicates equality of two objects
Let's take an example, the objects of the JobCandidate class are saved in ArrayList and ready to be sorted. The JobCandidate class has three member variables: string-type name and gender, Integer age. We want to sort the jobcandidate objects stored in ArrayList by age. So we want the JobCandidate class to implement the comparable interface and rewrite the CompareTo () method. The code for the
JobCandidate class is as follows:
jobcandidate.java

 package guru.springframework.blog.sortarraylist.comparable;
 public class JobCandidate implements comparable {private String name;
 Private String gender;
 private int age;
 Public jobcandidate (string name, string gender, int age) {this.name = name;
 This.gender = gender;
 This.age = age;
 Public String GetName () {return name;
 Public String Getgender () {return gender;
 public int getage () {return age; @Override public int CompareTo (jobcandidate candidate) {return (This.getage () < Candidate.getage ()?-1: (this. Getage () = = Candidate.getage ()?
 0:1)); 
 @Override public String toString () {return "Name: + THIS.name +", Gender: "+ This.gender +", Age: "+ this.age;" }
 }

In the CompareTo () method of the JobCandidate class overridden above, we implement the age based comparison logic. I've seen a lot of programmers take (This.getage () –candidate.getage ()) as the result of the return comparison. Although the use of this return statement may seem appealing and will not affect our example, my advice is to stay away from this statement. Imagine comparing an integer value in which one or two of the results are negative. This can lead to errors, make your program behave incorrectly, and more importantly, such bugs are subtle, especially in large enterprise applications that are difficult to detect. Here we'll write a helper class that sorts the ArrayList objects that contain the JobCandidate element for the delegate.
Jobcandidatesorter.java

Package guru.springframework.blog.sortarraylist.comparable;
Import java.util.ArrayList;
 Import java.util.Collections;
 public class Jobcandidatesorter {
 ArrayList jobcandidate = new arraylist<> ();
 Public Jobcandidatesorter (ArrayList jobcandidate) {
 this.jobcandidate = jobcandidate;
 }
 Public ArrayList Getsortedjobcandidatebyage () {
 collections.sort (jobcandidate);
 Return jobcandidate
 }
 }

In the Jobcandidatesorter class, we initialize a ArrayList object that the delegate will instantiate Jobcandidatesorter through the constructor. We then wrote the Getsortedjobcandidatebyage () method, in which we called Collections.sort () and passed the initialized ArrayList as parameters, finally returning the sorted ArrayList.
Next, we'll write a test class to test our code.
Jobcandidatesortertest.java

Package guru.springframework.blog.sortarraylist.comparable;
Import Org.junit.Test; Import Java.lang.reflect.Array; Import java.util.ArrayList; Import static org.junit.assert.*; public class Jobcandidatesortertest {<a href= ' Http://www.jobbole.com/members/madao ' > @Test </a> Public void Testgetsortedjobcandidatebyage () throws Exception {jobcandidate jobCandidate1 = new JobCandidate ("Mark Smith", "Mal E ", 26); JobCandidate jobCandidate2 = new JobCandidate ("Sandy Hunt", "Female", 23); JobCandidate jobCandidate3 = new JobCandidate ("Betty Clark", "Female", 20); JobCandidate jobCandidate4 = new JobCandidate ("Andrew Styne", "Male", 24); ArrayList jobcandidatelist = new arraylist<> (); Jobcandidatelist.add (JOBCANDIDATE1); Jobcandidatelist.add (JOBCANDIDATE2); Jobcandidatelist.add (JobCandidate3); Jobcandidatelist.add (JOBCANDIDATE4); Jobcandidatesorter jobcandidatesorter = new Jobcandidatesorter (jobcandidatelist); ArrayList sortedjobcandidate = Jobcandidatesorter.getsortedjobcandidatebyage (); SYSTEM.OUT.PRINTLN ("-----sorteD jobcandidate by age:ascending-----"); for (JobCandidate jobcandidate:sortedjobcandidate) {System.out.println (jobcandidate); } } }

In the test class above, we created four jobcandidate objects and added them to the ArrayList, then passed the ArrayList to the constructor to instantiate the Jobcandidatesorter class. Finally, we call the Getsortedjobcandidatebyage () method of the Jobcandidatesorter class and print the ArrayList of the sort returned by this method.

Using comparable to sort ArrayList is a common method. But you have to know there are certain limitations. The class of the object you want to sort must implement comparable and overwrite the CompareTo () method. This basically means that you will only be able to compare objects based on a member variable (the age field in our example). What if you were asked to sort the JobCandidate objects by name and age? Comparable is not the way to solve it. In addition, the comparison logic is part of the class of the object that needs to be compared, and it eliminates the possibility of more logical reusability. Java solves the above comparison requirements by using the comparator interface provided under the Java.util package.

Use Comparator to sort ArrayList

The Comparator interface, similar to the comparable interface, also provides a single comparison method called Compare (). However, unlike the CompareTo () method of comparable, this compare () accepts two different objects of the same type for comparison.
We'll use Comparator to sort the same JobCandidate class objects that we used before. We will allow the JobCandidate object to be sorted by age and name by implementing the Comparatoras anonymous inner class.
The following is the JobCandidate class code that uses the Comparator
Jobcandidate.java

Package guru.springframework.blog.sortarraylist.comparator;
 Import Java.util.Comparator;
 public class JobCandidate {private String name;
 Private String gender;
 private int age;
 Public jobcandidate (string name, string gender, int age) {this.name = name;
 This.gender = gender;
 This.age = age;
 Public String GetName () {return name;
 Public String Getgender () {return gender;
 public int getage () {return age; public static Comparator Agecomparator = new Comparator () {@Override public int compare (JobCandidate jc1, Jobcandida
 Te jc2) {return (Jc2.getage () < Jc1.getage ()?-1: (jc2.getage () = Jc1.getage ()? 0:1));
 }
 };  public static Comparator Namecomparator = new Comparator () {@Override public int compare (JobCandidate jc1, jobcandidate
 JC2) {return (int) (Jc1.getname (). CompareTo (Jc2.getname ()));
 }
 };
 @Override public String toString () {return "Name:" + THIS.name + ", Gender:" + This.gender + ", Age:" + this.age;
 }
 }

In the above class, from 29 lines to 35 lines, we wrote an anonymous class and implemented the compare () method to sort the JobCandidate objects in descending order of age. From 37 lines to 42 lines, we wrote an anonymous class and implemented the compare () method to sort the jobcandidate in ascending order of names. Now we write a class that sorts the ArrayList elements for the delegate.
Jobcandidatesorter.java

Package guru.springframework.blog.sortarraylist.comparator;
 Import java.util.ArrayList;
 Import java.util.Collections;
 public class Jobcandidatesorter {
 ArrayList jobcandidate = new arraylist<> ();
 Public Jobcandidatesorter (ArrayList jobcandidate) {
 this.jobcandidate = jobcandidate;
 }
 Public ArrayList Getsortedjobcandidatebyage () {
 collections.sort (jobcandidate, jobcandidate.agecomparator);
 return jobcandidate;
 }
 Public ArrayList Getsortedjobcandidatebyname () {
 collections.sort (jobcandidate, jobcandidate.namecomparator);
 Return jobcandidate
 }
 }

In the above class, we have written the Getsortedjobcandidatebyage () method, in which we call the overloaded version of Collections.sort (), which passes the ArrayList object to be sorted and the comparison age Comparator object. Inside the Getsortedjobcandidatebyname () method, we call another overloaded version of Collections.sort (), which passes the ArrayList object to be sorted and the Comparator object of the comparison name.
Let's write a test class to test our code.
Let's write a test class to test our code.
Jobcandidatesortertest.java

Package guru.springframework.blog.sortarraylist.comparator;
 Import Guru.springframework.blog.sortarraylist.comparator.JobCandidate;
 Import Guru.springframework.blog.sortarraylist.comparator.JobCandidateSorter;
 Import Org.junit.Before;
 Import Org.junit.Test;
 Import java.util.ArrayList;
 Import static org.junit.assert.*;
 public class Jobcandidatesortertest {Jobcandidatesorter jobcandidatesorter;
 @Before public void SetUp () throws Exception {jobcandidate jobCandidate1 = new JobCandidate ("Mark Smith", "Male", 26);
 JobCandidate jobCandidate2 = new JobCandidate ("Sandy Hunt", "Female", 23);
 JobCandidate jobCandidate3 = new JobCandidate ("Betty Clark", "Female", 20);
 JobCandidate jobCandidate4 = new JobCandidate ("Andrew Styne", "Male", 24);
 ArrayList jobcandidatelist = new arraylist<> ();
 Jobcandidatelist.add (JOBCANDIDATE1);
 Jobcandidatelist.add (JOBCANDIDATE2);
 Jobcandidatelist.add (JobCandidate3);
 Jobcandidatelist.add (JOBCANDIDATE4); Jobcandidatesorter = new JobcandidAtesorter (jobcandidatelist); } <a href= "Http://www.jobbole.com/members/madao" > @Test </a> public void Testgetsortedjobcandidatebyage ()
Throws Exception {System.out.println ("-----Sorted jobcandidate by age:descending-----");
 ArrayList sortedjobcandidate = Jobcandidatesorter.getsortedjobcandidatebyage ();
 for (JobCandidate jobcandidate:sortedjobcandidate) {System.out.println (jobcandidate); } <a href= "Http://www.jobbole.com/members/madao" > @Test </a> public void Testgetsortedjobcandidatebyname
() throws Exception {System.out.println ("-----Sorted jobcandidate by name:ascending-----");
 ArrayList sortedjobcandidate = Jobcandidatesorter.getsortedjobcandidatebyname ();
 for (JobCandidate jobcandidate:sortedjobcandidate) {System.out.println (jobcandidate); }
 }
 }

In the test class, we add several JobCandidate objects to the ArrayList and use before annotations to create a Jobcandidatesorter object in the test unit's setup () method. If you are a new JUnit novice, you can refer to my previous articles including JUnit annotations (JUnit Unit Test series). In the Testgetsortedjobcandidatebyage () test method we called the Getsortedjobcandidatebyage () method and printed the sorted ArrayList returned by the method. In the Testgetsortedjobcandidatebyname () test method we called the Getsortedjobcandidatebyname () method and also printed the ArrayList returned by the method.

In this article we have seen different methods of ArrayList ordering. One is using comparable and the other is using Comparator. The choice of methods has been one of the reasons why programmers are puzzled. The best thing to remember is that a comparable object can say "I can compare myself to another object" and a Comparator object can say "I can compare two different objects". You can't say one interface is better than another. The interface you choose depends on the functionality you need to implement.

The above is the entire content of this article, I hope to help you learn.

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.