Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to implement Comparable Interface in Integer

2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces "how to achieve Comparable interface inside Integer". In daily operation, I believe many people have doubts about how to achieve Comparable interface inside Integer. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to achieve Comparable interface inside Integer". Next, please follow the editor to study!

Why do you need to implement this interface?

First, take a look at an example of the data:

String [] strArr = {"A", "B", "C", "E", "D"}

Arrays.sort (strArr)

For (String string: strArr) {

System.out.print (string+ ";")

}

Output result:

A, B, C, D, E.

We can see that the sort method sorts the String strings in the data according to certain rules, so why is it sorted?

Looking at the String class, we can see:

Public final class String

Implements Serializable, Comparable, CharSequence {

...

}

It also implements the Comparable interface. The compareTo method is implemented in it, so it can be sorted according to some rules.

What if the object in the array is not a String but a custom type?

Public class ComparableDemo {

Public static void main (String [] args) {

Object [] objArray = {new Person (20, "jack"), new Person (17, "tom")

New Person (27, "aj")}

For (Object object: objArray) {

System.out.print (object.toString ())

}

Arrays.sort (objArray)

For (Object object: objArray) {

System.out.print (object.toString ())

}

}

}

Public class Person {

Private Integer age

Private String name

Public Person (int age,String name) {

This.age = age

This.name = name

}

@ Override

Public String toString () {

Return "Person [age=" + age + ", name=" + name + "]"

}

}

The result is:

Person [age=20, name=jack] Person [age=17, name=tom] Person [age=27, name=aj]

Exception in thread "main" java.lang.ClassCastException: interfacedemo.Person cannot be cast to java.lang.Comparable

At java.util.ComparableTimSort.countRunAndMakeAscending (Unknown Source)

At java.util.ComparableTimSort.sort (Unknown Source)

At java.util.ComparableTimSort.sort (Unknown Source)

At java.util.Arrays.sort (Unknown Source)

At interfacedemo.ComparableDemo.main (ComparableDemo.java:18)

You can see that it is normal to print without sorting, but the sorting Times is wrong. Because the system does not know what rules to use for sorting.

We saved the string sorting successfully because the String class has implemented the Comparable interface, so we also need to implement this interface if we want to implement custom object comparison, and the comparison method rules are set by ourselves.

II. Brief introduction of the interface

The list of objects (and arrays) that implement this interface can be sorted automatically through Collections.sort (and Arrays.sort). Objects that implement this interface can be used as keys in ordered maps or elements in ordered collections without specifying a comparator.

For every E1 and e2 of class C, the natural ordering of class C is called consistent with equals if and only if e1.compareTo (e2) = = 0 has the same boolean value as e1.equals (e2). Note that null is not an instance of any class, and even if e.equals (null) returns false,e.compareTo (null), NullPointerException will be thrown.

It is recommended (though not required) to make the natural ordering consistent with equals. This is because ordered sets (and ordered mapping tables) without explicit comparators behave "weird" when using elements (or keys) that are not naturally sorted with equals. In particular, such an ordered set (or ordered mapping table) violates the conventional protocol of a set (or mapping table) defined according to the equals method.

For example, if you add two keys an and b to an ordered set that does not use an explicit comparator so that (! a.equals (b) & & a.compareTo (b) = = 0), the second add operation returns false (the size of the ordered set does not increase), because from the point of view of the ordered set, an and b are equal.

In fact, all Java core classes that implement Comparable have a natural sort that is consistent with equals. Java.math.BigDecimal is an exception, and its natural ordering treats BigDecimal objects with equal values but different accuracy (such as 4.0,4.00) as equal.

Mathematically, the relationship that defines the natural ordering on a given class C is as follows:

{(x, y) | x.compareTo (y) 0 & & y.compareTo (z) > 0) means x.compareTo (z) > 0.

Finally, the implementer must ensure that x.compareTo (y) = = 0 means that sgn (x.compareTo (z)) = = sgn (y.compareTo (z)) exists for all z. This is highly recommended (x.compareTo (y) = = 0) = (x.equals (y)), but not strictly required. In general, any class that implements the Comparable interface and violates this condition should clearly point out this fact. The recommendation goes like this: "Note: this class has a natural ranking that is inconsistent with equals."

In the previous description, the symbol sgn (expression) specifies the signum mathematical function, which returns one of-1, 0, or 1, respectively, depending on whether the value of expression is negative, zero, or positive.

Parameters:

O-the object to compare.

Return:

A negative, zero, or positive integer, depending on whether the object is less than, equal to, or greater than the specified object.

Throw:

ClassCastException-if the type of the specified object does not allow it to be compared to this object.

At this point, the study on "how to implement the Comparable interface within Integer" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report