Java: Comparing and sorting

Source: Internet
Author: User
Tags comparable comparison sort

1. Two kinds of comparison interface analysis

There are two kinds of comparison interfaces in the collection framework: the comparable interface and the comparator interface. Comparable is a general-purpose interface that users can implement to perform their own specific comparisons, while comparator can be viewed as an implementation of an algorithm that specifies the comparator when a container set is implemented to compare functions, which can be viewed as a design pattern that separates the algorithm from the data.

The former should be more fixed and binding to a specific class, which is flexible and can be used for each class that needs to compare functions.

A class implements a Camparable interface that indicates that objects of this class can be compared to each other. If it is described in mathematical language, there is a whole sequence in the set of objects of this class. This way, the collection of class objects can be sorted by using the Sort method.

And the comparator has two functions:

1, if the class of designers do not take into account the problem of compare without the implementation of the comparable interface, can be achieved through the comparator comparison algorithm to sort;

2, in order to use different sorting criteria to prepare, such as: ascending, descending or other order.

2 Comparable interface

public interface Comparable<T> {
  public int compareTo(T o);
}

The Java.lang. Comparable interface defines the natural order of classes, and the classes that implement the interface can be sorted in this way.

1 int compareTo (object o): Compares the current instance object with the object o, returns a negative value if the object is in O, returns 0 if the two objects are in the same position in the sort, and returns a positive value if it is behind object o.

2 in Java 2 SDK version 1.4, there are 24 classes that implement the comparable interface. The following table shows the natural ordering of 8 basic types. Although some classes share the same natural ordering, only classes that are mutually comparable can be sorted.

Class Sort
Bigdecimal,biginteger,byte,double, Float,integer,long,short Sort by number size
Character Sort by number size for Unicode values
String Sort by character Unicode values in strings

Using the comparable interface to create the sort order of your own classes is simply a matter of implementing the CompareTo () method. It is usually a natural sort that relies on several data members. The class should also overwrite Equals () and hashcode () to ensure that two equal objects return the same hash code.

The function of this interface: if the array or the (class) element in the collection implements the interface, we can invoke Collections.sort and arrays.sort ordering, or apply it to an ordered set of TreeSet and TreeMap.

The following design an orderly class person, it implements the comparable interface, with age as the first keyword, the name of the second keyword in ascending order.

Person.java

Package com.zj.sort.comparable
public class person implements comparable<person> {
Private int a Ge
Private String name;    
Public person (int age, String name) {
This.age = age;
THIS.name = name;    
}
Public int compareTo {
int cop = Age-person.getage ();
    If (COP!= 0)
return cop;
  else
return Name.compareto (person.name);
  
public int getage () {
return age;
  
Public String GetName () {
return name;
   
public int hashcode () {
int result =;
result = Notoginseng * result + age;
result = Notoginseng * result + name.hashcode ();
return result;
}
Public boolean equals (Object o) {
if (!     o instanceof person),
return false;
person who = (person) o;
Return (age = = person.age) && (Name.equals (person.name));
}
Public String toString () {
retUrn (age + "{" + name + "}");
}
}

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.