Comparison of Java objects in the (study notes)

1) a detailed description of what the object comparison mode?

① Compared object reference ( "= =" operator)

"==" is the object reference to compare, in essence, whether the comparison of two reference variables refer to the same object. Note the point: when comparing string constants, JVM with a string constant to create only one object.

② comparison content (equals () method)

equals () methods compare the actual content of the two objects are the same. Note the point: from the source can be seen, equals () method will first do "==" comparison, only when the two variables are referenced when comparing the contents of different objects, save some resources.

③ Since Comparative defined object (java.util.Comparator interface and the interface java.lang.Comparable)

A.java.util.Comparator Interface:

Holding custom class does not change, a write outside this comparison algorithm (Comparative class) that implements the Comparator interface.

Comparator interface defines a compare (T o1, T o2) Method: Comparison of two parameters is used to sort.

/ * @Return O1 is less than, equal to or greater than o2, negative integer, zero or a positive integer. * /

In this case, the specific implementation compare () method with, and then transmitted to the Comparator Arrays.sort Collections.sort or implement sorting method.

B.java.lang.Comparable Interface:

Need for custom class changes, i.e., to achieve Comparable interface, it has the function of comparing.

Comparable interface defines a compareTo (T o) Method: Comparison this object with the specified object.

/ * @Return the object is less than, equal to or greater than O, a negative integer, zero or a positive integer. * /

Comparable interface imposes its object to realize a total ordering of each class, to achieve this object list (and arrays) may be performed automatically or sorted by Collection.sort Arrays.sort interface.

Examples can be seen, TreeSet constructor TreeSet (Comparator <? Super E> comparator) and TreeSet ().

 

2) with a life objects vividly illustrate the differences of Comparator and Comparable.

In English, tor the person is a common suffix, visi-tor (visitors), crea-tor (creator) ... personally think Comparator is like auto insurance company (third party), a major complex in the insurance accident company to the people, to contribute to assess Rules primary responsibility, secondary responsibility to divide the amount of insurance.

And able in English, it represents the ability to. A class implements the Comparable interface, which indicates that it has been given an ability to compare. Small cut rub accident, the two owners of privately negotiated compensation click on the finished thing.

Guess you like

Origin www.cnblogs.com/1693977889zz/p/11829448.html